Home

7 Tips to Handle undefined in JavaScript

Because JavaScript is permissive, developers have the temptation to access uninitialized values. I'm guilty of such bad practice too.

Often such risky actions generate undefined related errors:

  • TypeError: 'undefined' is not a function
  • TypeError: Cannot read property '<prop-name>' of undefined
  • and alike type errors .

JavaScript developers can understand the irony of this joke:

To reduce such errors, you have to understand the cases when undefined is generated. Let's explore undefined and its effect on code safety.

Before I go on, let me recommend something to you.

The path to becoming good at JavaScript isn't easy... but fortunately with a good teacher you can shortcut.

Take "Modern JavaScript From The Beginning 2.0" course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount!

Table of Contents

1. what is undefined, 2. scenarios that create undefined, 3. undefined in arrays, 4. undefined and null differences, 5. conclusion.

JavaScript has 6 primitive types:

  • Boolean: true or false
  • Number: 1 , 6.7 , 0xFF
  • String: "Gorilla and banana"
  • Symbol: Symbol("name") (starting ES2015)
  • Undefined: undefined .

And a separated object type: {name: "Dmitri"} , ["apple", "orange"] .

From 6 primitive types undefined is a special value with its own type Undefined. According to ECMAScript specification :

Undefined value primitive value is used when a variable has not been assigned a value.

The standard clearly defines that you will receive undefined when accessing uninitialized variables, non-existing object properties, non-existing array elements, and alike.

A few examples:

The above example demonstrates that accessing:

  • an uninitialized variable number
  • a non-existing object property movie.year
  • or a non-existing array element movies[3]

are evaluated as undefined .

The ECMAScript specification defines the type of undefined value:

Undefined type is a type whose sole value is the undefined value.

In this sense, typeof operator returns 'undefined' string for an undefined value:

Of course typeof works nicely to verify whether a variable contains an undefined value:

2.1 Uninitialized variable

A declared variable but not yet assigned with a value ( uninitialized ) is undefined .

Plain and simple:

myVariable is declared and not yet assigned with a value. Accessing the variable evaluates to undefined .

An efficient approach to solve the troubles of uninitialized variables is whenever possible to assign an initial value . The less the variable exists in an uninitialized state, the better.

Ideally, you would assign a value right away after declaration const myVariable = 'Initial value' . But that's not always possible.

Tip 1: Favor const , otherwise use let , but say goodbye to var

const and let are block scoped (contrary to older function scoped var ) and exist in a temporal dead zone until the declaration line.

If you want to define a variable, always start with const , which creates an immutable binding .

One of the nice features of const is that you must assign an initial value to the variable const myVariable = 'initial' . The variable is not exposed to the uninitialized state and accessing undefined is impossible.

Let's check the function that verifies whether a word is a palindrome:

length and half variables are assigned with a value once. It seems reasonable to declare them as const since these variables aren't going to change.

Use let declaration for variables whose value can change. Whenever possible assign an initial value right away, e.g. let index = 0 .

What about the old-school var ? My suggestion is to stop using it .

var declaration problem is the variable hoisting within the function scope. You can declare a var variable somewhere at the end of the function scope, but still, you can access it before declaration: and you'll get an undefined .

myVariable is accessible and contains undefined even before the declaration line: var myVariable = 'Initial value' .

Contrary, a const or let variable cannot be accessed before the declaration line — the variable is in a temporal dead zone before the declaration. And that's nice because you have less chance to access an undefined .

The above example updated with let (instead of var ) throws a ReferenceError because the variable in the temporal dead zone is not accessible.

Encouraging the usage of const for immutable bindings or let otherwise ensures a practice that reduces the appearance of the uninitialized variable.

Tip 2: Increase cohesion

Cohesion characterizes the degree to which the elements of a module (namespace, class, method, block of code) belong together. The cohesion can be high or low .

A high cohesion module is preferable because the elements of such a module focus solely on a single task. It makes the module:

  • Focused and understandable : easier to understand what the module does
  • Maintainable and easier to refactor : the change in the module affects fewer modules
  • Reusable : being focused on a single task, makes the module easier to reuse
  • Testable : it's easier to test a module that's focused on a single task

High cohesion accompanied by loose coupling is the characteristic of a well-designed system.

A code block can be considered a small module. To profit from the benefits of high cohesion, keep the variables as close as possible to the code block that uses them.

For instance, if a variable solely exists to form the logic of block scope, then declare and make the variable exist only within that block (using const or let declarations). Do not expose this variable to the outer block scope, since the outer block shouldn't need this variable.

One classic example of the unnecessarily extended life of variables is the usage of for cycle inside a function:

index , item , and length variables are declared at the beginning of the function body. However, they are used only near the end. What's the problem with this approach?

Between the declaration at the top and the usage in for statement the variables index and item are uninitialized and exposed to undefined . They have an unreasonably long lifecycle in the entire function scope.

A better approach is to move these variables as close as possible to their usage place:

index and item variables exist only in the block scope of for statement. They don't have any meaning outside of for . length variable is declared close to the source of its usage too.

The refactored code is better because:

  • The variables are not exposed to an uninitialized state, thus you have no risk of accessing undefined
  • Moving the variables as close as possible to their usage place increases the code readability
  • High cohesive chunks of code are easier to refactor and extract into separate functions, if necessary

2.2 Accessing a non-existing property

When accessing a non-existing object property , JavaScript returns undefined .

Let's demonstrate that in an example:

favoriteMovie is an object with a single property title . Accessing a non-existing property actors using a property accessor favoriteMovie.actors evaluates to undefined .

Accessing a non-existing property does not throw an error. The problem appears when trying to get data from the non-existing property (e.g. favoriteMovie.actors.length ) — the most common undefined issue.

"TypeError: Cannot read property <prop> of undefined" is a very common error message generated by accessing data from non-existing properties.

Let's slightly modify the previous code snippet to illustrate a TypeError throw:

favoriteMovie does not have the property actors , so favoriteMovie.actors evaluates to undefined .

As a result, accessing the length of an undefined value using the expression favoriteMovie.actors.length throws a TypeError .

A good way to bypass this problem is to restrict the object to have always defined the properties that it holds.

Unfortunately, often you don't have control over the objects. Such objects may have a different set of properties in diverse scenarios. So you have to handle all these scenarios manually.

Let's implement a function append(array, toAppend) that adds at the beginning and/or at the end of an array new elements. toAppend parameter accepts an object with properties:

  • first : element inserted at the beginning of array
  • last : element inserted at the end of array .

The function returns a new array instance, without altering the original array.

The first version of append() , a bit naive, may look like this:

Because toAppend object can omit first or last properties, it is obligatory to verify whether these properties exist in toAppend .

A property accessor evaluates to undefined if the property does not exist. The first temptation to check whether first or last properties are present is to verify them against undefined . This is performed in conditionals if(toAppend.first){} and if(toAppend.last){} ...

Not so fast. This approach has a drawback. undefined , as well as false , null , 0 , NaN , and '' are falsy values.

In the current implementation of append() , the function doesn't allow to insert falsy elements:

0 and false are falsy. Because if(toAppend.first){} and if(toAppend.last){} actually compare against falsy, these elements are not inserted into the array. The function returns the initial array [10] without modifications, instead of the expected [0, 10, false] .

The tips that follow explain how to correctly check the property's existence.

Tip 3: Check the property existence

Fortunately, JavaScript offers a bunch of ways to determine if the object has a specific property:

  • obj.prop !== undefined : compare against undefined directly
  • typeof obj.prop !== 'undefined' : verify the property value type
  • obj.hasOwnProperty('prop') : verify whether the object has its own property
  • 'prop' in obj : verify whether the object has an own or inherited property

My recommendation is to use in operator. It has a short and readable syntax. in operator presence suggests a clear intent of checking whether an object has a specific property, without accessing the actual property value.

obj.hasOwnProperty('prop') is a nice solution too. It's slightly longer than in operator and verifies only the object's own properties.

Let's improve append(array, toAppend) function using in operator:

in operator fixes the problem by inserting falsy elements 0 and false . Now, adding these elements at the beginning and the end of [10] produces the expected result [0, 10, false] .

Tip 4: Destructuring to access object properties

When accessing an object property, sometimes it's necessary to set a default value if the property does not exist.

You might use in accompanied with a ternary operator to accomplish this:

Ternary operator syntax becomes daunting when the number of properties to check increases. For each property, you have to create a new line of code to handle the defaults, increasing an ugly wall of similar-looking ternary operators.

To use a more elegant approach, let's get familiar with a great ES2015 feature called object destructuring .

Object destructuring allows inline extraction of object properties directly into variables and sets a default value if the property does not exist. A convenient syntax to avoid dealing directly with undefined .

Indeed, the property extraction is better:

To see things in action, let's define a useful function that wraps a string in quotes.

quote(subject, config) accepts the first argument as the string to be wrapped. The second argument config is an object with the properties:

  • char : the quote char, e.g. ' (single quote) or " (double quote). Defaults to " .
  • skipIfQuoted : the boolean value to skip quoting if the string is already quoted. Defaults to true .

Applying the benefits of object destructuring, let's implement quote() :

const { char = '"', skipIfQuoted = true } = config destructuring assignment in one line extracts the properties char and skipIfQuoted from config object.

If some properties are missing in the config object, the destructuring assignment sets the default values: '"' for char and false for skipIfQuoted .

Fortunately, the function still has room for improvement.

Let's move the destructuring assignment into the parameters section. And set a default value (an empty object { } ) for the config parameter, to skip the second argument when default settings are enough.

The destructuring assignment replaces the config parameter in the function's signature. I like that: quote() becomes one line shorter.

= {} on the right side of the destructuring assignment ensures that an empty object is used if the second argument is not indicated during the call: quote('Sunny day') .

Object destructuring is a powerful feature that handles efficiently the extraction of properties from objects. I like the possibility to specify a default value to be returned when the accessed property doesn't exist. As a result, you avoid undefined and the hassle around it.

Tip 5: Fill the object with default properties

If there is no need to create variables for every property, as the destructuring assignment does, the object that misses some properties can be filled with default values.

Object.assign(target, source1, source2, ...) copies the values of all enumerable own properties from one or more source objects into the target object. The function returns the target object.

For instance, you need to access the properties of unsafeOptions object that doesn't always contain its full set of properties.

To avoid undefined when accessing a non-existing property from unsafeOptions , let's make some adjustments:

  • Define an object defaults that holds the default property values
  • Call Object.assign({ }, defaults, unsafeOptions) to build a new object options . The new object receives all properties from unsafeOptions , but the missing ones are taken from defaults .

unsafeOptions contains only fontSize property. defaults object defines the default values for properties fontSize and color .

Object.assign() takes the first argument as a target object {} . The target object receives the value of fontSize property from unsafeOptions source object. And the value of color property from defaults source object, because unsafeOptions doesn't contain color .

The order in which the source objects are enumerated does matter: later source object properties overwrite earlier ones.

You are now safe to access any property of options object, including options.color that wasn't available in unsafeOptions initially.

Fortunately, an easier alternative to fill the object with default properties exists. I recommend using the spread properties in object initializers .

Instead of Object.assign() , use the object spread syntax to copy into the target object all own and enumerable properties from source objects:

The object initializer spreads properties from defaults and unsafeOptions source objects. The order in which the source objects are specified is important: later source object properties overwrite earlier ones.

Filling an incomplete object with default property values is an efficient strategy to make your code safe and durable. No matter the situation, the object always contains the full set of properties: and undefined cannot be generated.

Bonus tip: nullish coalescing

The operator nullish coalescing evaluates to a default value when its operand is undefined or null :

Nullish coalescing operator is convenient to access an object property while having a default value when this property is undefined or null :

styles object doesn't have the property color , thus styles.color property accessor is undefined . styles.color ?? 'black' evaluates to the default value 'black' .

styles.fontSize is 18 , so the nullish coalescing operator evaluates to the property value 18 .

2.3 Function parameters

The function parameters implicitly default to undefined .

Usually, a function defined with a specific number of parameters should be invoked with the same number of arguments. That's when the parameters get the values you expect:

When calling multiply(5, 3) , the parameters a and b receive 5 and respectively 3 values. The multiplication is calculated as expected: 5 * 3 = 15 .

What does happen when you omit an argument on invocation? The corresponding parameter inside the function becomes undefined .

Let's slightly modify the previous example by calling the function with just one argument:

The invocation multiply(5) is performed with a single argument: as a result a parameter is 5 , but the b parameter is undefined .

Tip 6: Use default parameter value

Sometimes a function does not require the full set of arguments on invocation. You can set defaults for parameters that don't have a value.

Recalling the previous example, let's make an improvement. If b parameter is undefined , let default it to 2 :

The function is invoked with a single argument multiply(5) . Initially, a parameter is 2 and b is undefined .

The conditional statement verifies whether b is undefined . If it happens, b = 2 assignment sets a default value.

While the provided way to assign default values works, I don't recommend comparing directly against undefined . It's verbose and looks like a hack.

A better approach is to use the ES2015 default parameters feature. It's short, expressive, and has no direct comparisons with undefined .

Adding a default value to parameter b = 2 looks better:

b = 2 in the function signature makes sure that if b is undefined , the parameter defaults to 2 .

The default parameters feature is intuitive and expressive. Always use it to set default values for optional parameters.

2.4 Function return value

Implicitly, without return statement, a JavaScript function returns undefined .

A function that doesn't have return statement implicitly returns undefined :

square() function does not return any computation results. The function invocation result is undefined .

The same situation happens when return statement is present, but without an expression nearby:

return; statement is executed, but it doesn't return any expression. The invocation result is also undefined .

Of course, indicating near return the expression to be returned works as expected:

Now the function invocation is evaluated to 4 , which is 2 squared.

Tip 7: Don't trust the automatic semicolon insertion

The following list of statements in JavaScript must end with semicolons ( ; ):

  • empty statement
  • let , const , var , import , export declarations
  • expression statement
  • debugger statement
  • continue statement, break statement
  • throw statement
  • return statement

If you use one of the above statements, be sure to indicate a semicolon at the end:

At the end of both let declaration and return statement an obligatory semicolon is written.

What happens when you don't want to indicate these semicolons? In such a situation ECMAScript provides an Automatic Semicolon Insertion (ASI) mechanism, which inserts for you the missing semicolons.

Helped by ASI, you can remove the semicolons from the previous example:

The above text is a valid JavaScript code. The missing semicolons are automatically inserted for you.

At first sight, it looks pretty promising. ASI mechanism lets you skip the unnecessary semicolons. You can make the JavaScript code smaller and easier to read.

There is one small, but annoying trap created by ASI. When a newline stands between return and the returned expression return \n expression , ASI automatically inserts a semicolon before the newline return; \n expression .

What does it mean to have return; statement inside of a function? The function returns undefined . If you don't know in detail the mechanism of ASI, the unexpectedly returned undefined is misleading.

For instance, let's study the returned value of getPrimeNumbers() invocation:

Between return statement and the array literal expression exists a new line. JavaScript automatically inserts a semicolon after return , interpreting the code as follows:

The statement return; makes the function getPrimeNumbers() return undefined instead of the expected array.

The problem is solved by removing the newline between return and array literal:

My recommendation is to study how exactly Automatic Semicolon Insertion works to avoid such situations.

Of course, never put a newline between return and the returned expression.

2.5 void operator

void <expression> evaluates the expression and returns undefined no matter the result of the evaluation.

One use case of void operator is to suppress expression evaluation to undefined , relying on some side-effect of the evaluation.

You get undefined when accessing an array element with an out-of-bounds index.

colors array has 3 elements, thus valid indexes are 0 , 1 , and 2 .

Because there are no array elements at indexes 5 and -1 , the accessors colors[5] and colors[-1] are undefined .

In JavaScript, you might encounter so-called sparse arrays . These are arrays that have gaps, i.e. at some indexes no elements are defined.

When a gap (aka empty slot) is accessed inside a sparse array, you also get an undefined .

The following example generates sparse arrays and tries to access their empty slots:

sparse1 is created by invoking an Array constructor with a numeric first argument. It has 3 empty slots.

sparse2 is created with an array literal with the missing second element.

In any of these sparse arrays accessing an empty slot evaluates to undefined .

When working with arrays, to avoid undefined , be sure to use valid array indexes and prevent the creation of sparse arrays.

What is the main difference between undefined and null ? Both special values imply an empty state.

undefined represents the value of a variable that hasn't been yet initialized , while null represents an intentional absence of an object .

Let's explore the difference in some examples.

The variable number is defined, however, is not assigned with an initial value:

number variable is undefined , which indicates an uninitialized variable.

The same uninitialized concept happens when a non-existing object property is accessed:

Because lastName property does not exist in obj , JavaScript evaluates obj.lastName to undefined .

On the other side, you know that a variable expects an object. But for some reason, you can't instantiate the object. In such case null is a meaningful indicator of a missing object .

For example, clone() is a function that clones a plain JavaScript object. The function is expected to return an object:

However clone() might be invoked with a non-object argument: 15 or null . The function cannot create a clone from these values, so it returns null — the indicator of a missing object.

typeof operator makes the distinction between undefined and null :

Also the strict quality operator === correctly differentiates undefined from null :

undefined existence is a consequence of JavaScript's permissive nature that allows the usage of:

  • uninitialized variables
  • non-existing object properties or methods
  • out-of-bounds indexes to access array elements
  • the invocation result of a function that returns nothing

Comparing directly against undefined is unsafe because you rely on a permitted but discouraged practice mentioned above.

An efficient strategy is to reduce the appearance of undefined keyword in your code by applying good habits such as:

  • reduce the usage of uninitialized variables
  • make the variables' lifecycle short and close to the source of their usage
  • whenever possible assign initial values to variables
  • favor const , otherwise use let
  • use default values for insignificant function parameters
  • verify the properties' existence or fill the unsafe objects with default properties
  • avoid the usage of sparse arrays

Is it good or bad that JavaScript has undefined and null to represent empty values?

Like the post? Please share!

Dmitri Pavlutin

Optional chaining '?.'

The optional chaining ?. is a safe way to access nested object properties, even if an intermediate property doesn’t exist.

The “non-existing property” problem

If you’ve just started to read the tutorial and learn JavaScript, maybe the problem hasn’t touched you yet, but it’s quite common.

As an example, let’s say we have user objects that hold the information about our users.

Most of our users have addresses in user.address property, with the street user.address.street , but some did not provide them.

In such case, when we attempt to get user.address.street , and the user happens to be without an address, we get an error:

That’s the expected result. JavaScript works like this. As user.address is undefined , an attempt to get user.address.street fails with an error.

In many practical cases we’d prefer to get undefined instead of an error here (meaning “no street”).

…and another example. In Web development, we can get an object that corresponds to a web page element using a special method call, such as document.querySelector('.elem') , and it returns null when there’s no such element.

Once again, if the element doesn’t exist, we’ll get an error accessing .innerHTML property of null . And in some cases, when the absence of the element is normal, we’d like to avoid the error and just accept html = null as the result.

How can we do this?

The obvious solution would be to check the value using if or the conditional operator ? , before accessing its property, like this:

It works, there’s no error… But it’s quite inelegant. As you can see, the "user.address" appears twice in the code.

Here’s how the same would look for document.querySelector :

We can see that the element search document.querySelector('.elem') is actually called twice here. Not good.

For more deeply nested properties, it becomes even uglier, as more repetitions are required.

E.g. let’s get user.address.street.name in a similar fashion.

That’s just awful, one may even have problems understanding such code.

There’s a little better way to write it, using the && operator:

AND’ing the whole path to the property ensures that all components exist (if not, the evaluation stops), but also isn’t ideal.

As you can see, property names are still duplicated in the code. E.g. in the code above, user.address appears three times.

That’s why the optional chaining ?. was added to the language. To solve this problem once and for all!

Optional chaining

The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined .

Further in this article, for brevity, we’ll be saying that something “exists” if it’s not null and not undefined .

In other words, value?.prop :

  • works as value.prop , if value exists,
  • otherwise (when value is undefined/null ) it returns undefined .

Here’s the safe way to access user.address.street using ?. :

The code is short and clean, there’s no duplication at all.

Here’s an example with document.querySelector :

Reading the address with user?.address works even if user object doesn’t exist:

Please note: the ?. syntax makes optional the value before it, but not any further.

E.g. in user?.address.street.name the ?. allows user to safely be null/undefined (and returns undefined in that case), but that’s only for user . Further properties are accessed in a regular way. If we want some of them to be optional, then we’ll need to replace more . with ?. .

We should use ?. only where it’s ok that something doesn’t exist.

For example, if according to our code logic user object must exist, but address is optional, then we should write user.address?.street , but not user?.address?.street .

Then, if user happens to be undefined, we’ll see a programming error about it and fix it. Otherwise, if we overuse ?. , coding errors can be silenced where not appropriate, and become more difficult to debug.

If there’s no variable user at all, then user?.anything triggers an error:

The variable must be declared (e.g. let/const/var user or as a function parameter). The optional chaining works only for declared variables.

Short-circuiting

As it was said before, the ?. immediately stops (“short-circuits”) the evaluation if the left part doesn’t exist.

So, if there are any further function calls or operations to the right of ?. , they won’t be made.

For instance:

Other variants: ?.(), ?.[]

The optional chaining ?. is not an operator, but a special syntax construct, that also works with functions and square brackets.

For example, ?.() is used to call a function that may not exist.

In the code below, some of our users have admin method, and some don’t:

Here, in both lines we first use the dot ( userAdmin.admin ) to get admin property, because we assume that the user object exists, so it’s safe read from it.

Then ?.() checks the left part: if the admin function exists, then it runs (that’s so for userAdmin ). Otherwise (for userGuest ) the evaluation stops without errors.

The ?.[] syntax also works, if we’d like to use brackets [] to access properties instead of dot . . Similar to previous cases, it allows to safely read a property from an object that may not exist.

Also we can use ?. with delete :

The optional chaining ?. has no use on the left side of an assignment.

For example:

The optional chaining ?. syntax has three forms:

  • obj?.prop – returns obj.prop if obj exists, otherwise undefined .
  • obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined .
  • obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined .

As we can see, all of them are straightforward and simple to use. The ?. checks the left part for null/undefined and allows the evaluation to proceed if it’s not so.

A chain of ?. allows to safely access nested properties.

Still, we should apply ?. carefully, only where it’s acceptable, according to our code logic, that the left part doesn’t exist. So that it won’t hide programming errors from us, if they occur.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy
  • Skip to main content
  • Select language
  • Skip to search
  • Conditional (ternary) Operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

Description

If condition is true , the operator returns the value of expr1 ; otherwise, it returns the value of expr2 . For example, to display a different message based on the value of the isMember variable, you could use this statement:

You can also assign variables depending on a ternary result:

Multiple ternary evaluations are also possible (note: the conditional operator is right associative):

You can also use multiple conditions like in a multiple-conditions IF statement

Note: The parentheses are not required, and do not affect the functionality. They are there to help visualize how the outcome is processed.

You can also use ternary evaluations in free space in order to do different operations:

You can also do more than one single operation per case, separating them with a comma:

You can also do more than one operation during the assignation of a value. In this case, the last comma-separated value of the parenthesis will be the value to be assigned .

Specifications

Browser compatibility.

  • if statement

Document Tags and Contributors

  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

JavaScript Check if Undefined – How to Test for Undefined in JS

An undefined variable or anything without a value will always return "undefined" in JavaScript. This is not the same as null, despite the fact that both imply an empty state.

You'll typically assign a value to a variable after you declare it, but this is not always the case.

When a variable is declared or initialized but no value is assigned to it, JavaScript automatically displays "undefined". It looks like this:

Also, when you try accessing values in, for example, an array or object that doesn’t exist, it will throw undefined .

Here's another example:

In this article, you will learn the various methods and approaches you can use to know if a variable is undefined in JavaScript. This is necessary if you want to avoid your code throwing errors when performing an operation with an undefined variable.

In case you are in a rush, here are the three standard methods that can help you check if a variable is undefined in JavaScript:

Let’s now explain each of these methods in more detail.

How to Check if a Variable is Undefined in JavaScript with Direct Comparison

One of the first methods that comes to mind is direct comparison. This is where you compare the output to see if it returns undefined . You can easily do this in the following way:

This also works for arrays as you can see below:

And it definitely also works for other variables:

How to Check if a Variable is Undefined in JavaScript with typeof

We can also use the type of the variable to check if it’s undefined . Luckily for us undefined is a datatype for an undefined value as you can see below: ‌

With this we can now use the datatype to check undefined for all types of data as we saw above. Here is what the check will look like for all three scenarios we have considered:

How to Check if a Variable is Undefined in JavaScript with the Void Operator

The void operator is often used to obtain the undefined primitive value. You can do this using " void(0) " which is similar to " void 0 " as you can see below:

In the actual sense, this works like direct comparison (which we saw before). But we would replace undefined with void(0) or void 0 as seen below:

Or like this:

In this article, we learned how to check if a variable is undefined and what causes a variable to be undefined.

We also learned three methods we can use to check if a variable is undefined. All methods work perfectly. Choosing your preferred method is totally up to you.

Have fun coding!

Frontend Developer & Technical Writer

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

javascript conditional assignment undefined

Announcing TypeScript 5.4

javascript conditional assignment undefined

Daniel Rosenwasser

March 6th, 2024 0 0

Today we’re excited to announce the release of TypeScript 5.4!

If you’re not familiar with TypeScript, it’s a language that builds on top of JavaScript by making it possible to declare and describe types. Writing types in our code allows us to explain intent and have other tools check our code to catch mistakes like typos, issues with null and undefined , and more. Types also power TypeScript’s editor tooling like the auto-completion, code navigation, and refactorings that you might see in Visual Studio and VS Code. In fact, if you’ve been writing JavaScript in either of those editors, you’ve been using TypeScript all this time!

To get started using TypeScript through NuGet or through npm with the following command:

Here’s a quick list of what’s new in TypeScript 5.4!

Preserved Narrowing in Closures Following Last Assignments

The noinfer utility type, object.groupby and map.groupby, support for require() calls in --moduleresolution bundler and --module preserve, checked import attributes and assertions, quick fix for adding missing parameters, auto-import support for subpath imports.

  • Upcoming 5.5 Deprecations

Notable Behavioral Changes

What’s new since the beta and rc.

Since the beta, we’ve updated the release notes to document new notable behavioral changes , including restrictions around enum compatibility, restrictions on enum member naming, and improvements in mapped type behavior.

Since the release candidate, we’ve documented our new auto-import support for subpath imports .

TypeScript can usually figure out a more specific type for a variable based on checks that you might perform. This process is called narrowing.

One common pain-point was that these narrowed types weren’t always preserved within function closures.

Here, TypeScript decided that it wasn’t "safe" to assume that url was actually a URL object in our callback function because it was mutated elsewhere; however, in this instance, that arrow function is always created after that assignment to url , and it’s also the last assignment to url .

TypeScript 5.4 takes advantage of this to make narrowing a little smarter. When parameters and let variables are used in non- hoisted functions, the type-checker will look for a last assignment point. If one is found, TypeScript can safely narrow from outside the containing function. What that means is the above example just works now.

Note that narrowing analysis doesn’t kick in if the variable is assigned anywhere in a nested function. This is because there’s no way to know for sure whether the function will be called later.

This should make lots of typical JavaScript code easier to express. You can read more about the change on GitHub .

When calling generic functions, TypeScript is able to infer type arguments from whatever you pass in.

One challenge, however, is that it is not always clear what the "best" type is to infer. This might lead to TypeScript rejecting valid calls, accepting questionable calls, or just reporting worse error messages when it catches a bug.

For example, let’s imagine a createStreetLight function that takes a list of color names, along with an optional default color.

What happens when we pass in a defaultColor that wasn’t in the original colors array? In this function, colors is supposed to be the "source of truth" and describe what can be passed to defaultColor .

In this call, type inference decided that "blue" was just as valid of a type as "red" or "yellow" or "green" . So instead of rejecting the call, TypeScript infers the type of C as "red" | "yellow" | "green" | "blue" . You might say that inference just blue up in our faces!

One way people currently deal with this is to add a separate type parameter that’s bounded by the existing type parameter.

This works, but is a little bit awkward because D probably won’t be used anywhere else in the signature for createStreetLight . While not bad in this case , using a type parameter only once in a signature is often a code smell.

That’s why TypeScript 5.4 introduces a new NoInfer<T> utility type. Surrounding a type in NoInfer<...> gives a signal to TypeScript not to dig in and match against the inner types to find candidates for type inference.

Using NoInfer , we can rewrite createStreetLight as something like this:

Excluding the type of defaultColor from being explored for inference means that "blue" never ends up as an inference candidate, and the type-checker can reject it.

You can see the specific changes in the implementing pull request , along with the initial implementation provided thanks to Mateusz Burzyński !

TypeScript 5.4 adds declarations for JavaScript’s new Object.groupBy and Map.groupBy static methods.

Object.groupBy takes an iterable, and a function that decides which "group" each element should be placed in. The function needs to make a "key" for each distinct group, and Object.groupBy uses that key to make an object where every key maps to an array with the original element in it.

So the following JavaScript:

is basically equivalent to writing this:

Map.groupBy is similar, but produces a Map instead of a plain object. This might be more desirable if you need the guarantees of Map s, you’re dealing with APIs that expect Map s, or you need to use any kind of key for grouping – not just keys that can be used as property names in JavaScript.

and just as before, you could have created myObj in an equivalent way:

Note that in the above example of Object.groupBy , the object produced uses all optional properties.

This is because there’s no way to guarantee in a general way that all the keys were produced by groupBy .

Note also that these methods are only accessible by configuring your target to esnext or adjusting your lib settings. We expect they will eventually be available under a stable es2024 target.

We’d like to extend a thanks to Kevin Gibbons for adding the declarations to these groupBy methods .

TypeScript has a moduleResolution option called bundler that is meant to model the way modern bundlers figure out which file an import path refers to. One of the limitations of the option is that it had to be paired with --module esnext , making it impossible to use the import ... = require(...) syntax.

That might not seem like a big deal if you’re planning on just writing standard ECMAScript import s, but there’s a difference when using a package with conditional exports .

In TypeScript 5.4, require() can now be used when setting the module setting to a new option called preserve .

Between --module preserve and --moduleResolution bundler , the two more accurately model what bundlers and runtimes like Bun will allow, and how they’ll perform module lookups. In fact, when using --module preserve , the bundler option will be implicitly set for --moduleResolution (along with --esModuleInterop and --resolveJsonModule )

Under --module preserve , an ECMAScript import will always be emitted as-is, and import ... = require(...) will be emitted as a require() call (though in practice you may not even use TypeScript for emit, since it’s likely you’ll be using a bundler for your code). This holds true regardless of the file extension of the containing file. So the output of this code:

should look something like this:

What this also means is that the syntax you choose directs how conditional exports are matched. So in the above example, if the package.json of some-package looks like this:

TypeScript will resolve these paths to [...]/some-package/esm/foo-from-import.mjs and [...]/some-package/cjs/bar-from-require.cjs .

For more information, you can read up on these new settings here .

Import attributes and assertions are now checked against the global ImportAttributes type. This means that runtimes can now more accurately describe the import attributes

This change was provided thanks to Oleksandr Tarasiuk .

TypeScript now has a quick fix to add a new parameter to functions that are called with too many arguments.

A quick fix being offered when someFunction calls someHelperFunction with 2 more arguments than are expected.

This can be useful when threading a new argument through several existing functions, which can be cumbersome today.

This quick fix was provided courtsey of Oleksandr Tarasiuk .

In Node.js, package.json supports a feature called "subpath imports" via a field called imports s . It’s a way to re-mapping paths inside of a package to other module paths. Conceptually, this is pretty similar to path-mapping, a featue that certain module bundlers and loaders support (and which TypeScript supports via a feature called paths ). The only difference is that subpath imports always have to start with a # .

TypeScript’s auto-imports feature previously did not consider paths in imports which could be frustrating. Instead, users might have to manually define paths in their tsconfig.json . However, thanks to a contribution from Emma Hamilton , TypeScript’s auto-imports now support subpath imports !

Upcoming Changes from TypeScript 5.0 Deprecations

TypeScript 5.0 deprecated the following options and behaviors:

  • target: ES3
  • importsNotUsedAsValues
  • noImplicitUseStrict
  • noStrictGenericChecks
  • keyofStringsOnly
  • suppressExcessPropertyErrors
  • suppressImplicitAnyIndexErrors
  • preserveValueImports
  • prepend in project references
  • implicitly OS-specific newLine

To continue using them, developers using TypeScript 5.0 and other more recent versions have had to specify a new option called ignoreDeprecations with the value "5.0" .

However, TypScript 5.4 will be the last version in which these will continue to function as normal. By TypeScript 5.5 (likely June 2024), these will become hard errors, and code using them will need to be migrated away.

For more information, you can read up on this plan on GitHub , which contains suggestions in how to best adapt your codebase.

This section highlights a set of noteworthy changes that should be acknowledged and understood as part of any upgrade. Sometimes it will highlight deprecations, removals, and new restrictions. It can also contain bug fixes that are functionally improvements, but which can also affect an existing build by introducing new errors.

lib.d.ts Changes

Types generated for the DOM may have an impact on type-checking your codebase. For more information, see the DOM updates for TypeScript 5.4 .

More Accurate Conditional Type Constraints

The following code no longer allows the second variable declaration in the function foo .

Previously, when TypeScript checked the initializer for second , it needed to determine whether IsArray<U> was assignable to the unit type false . While IsArray<U> isn’t compatible any obvious way, TypeScript looks at the constraint of that type as well. In a conditional type like T extends Foo ? TrueBranch : FalseBranch , where T is generic, the type system would look at the constraint of T , substitute it in for T itself, and decide on either the true or false branch.

But this behavior was inaccurate because it was overly-eager. Even if the constraint of T isn’t assignable to Foo , that doesn’t mean that it won’t be instantiated with something that is. And so the more correct behavior is to produce a union type for the constraint of the conditional type in cases where it can’t be proven that T never or always extends Foo.

TypeScript 5.4 adopts this more accuratre behavior. What this means in practice is that you may begin to find that some conditional type instances are no longer compatible with their branches.

You can read about the specific changes here .

More Aggressive Reduction of Intersections Between Type Variables and Primitive Types

TypeScript now reduces intersections with type variables and primitives more aggressively, depending on how the type variable’s constraint overlaps with those primitives.

For more information, see the change here .

Improved Checking Against Template Strings with Interpolations

TypeScript now more accurately checks whether or not strings are assignable to the placeholder slots of a template string type.

This behavior is more desirable, but may cause breaks in code using constructs like conditional types, where these rule changes are easy to witness.

See this change for more details.

Errors When Type-Only Imports Conflict with Local Values

Previously, TypeScript would permit the following code under isolatedModules if the import to Something only referred to a type.

However, it’s not safe for a single-file compilers to assume whether it’s "safe" to drop the import , even if the code is guaranteed to fail at runtime. In TypeScript 5.4, this code will trigger an error like the following:

The fix should be to either make a local rename, or, as the error states, add the type modifier to the import:

See more information on the change itself .

New Enum Assignability Restrictions

When two enums have the same declared names and enum member names, they were previously always considered compatible; however, when the values were known, TypeScript would silently allow them to have differing values.

TypeScript 5.4 tightens this restriction by requiring the values to be identical when they are known.

Additionally, there are new restrictions for when one of the enum members does not have a statically-known value. In these cases, the other enum must at least be implicitly numeric (e.g. it has no statically resolved initializer), or it is explicitly numeric (meaning TypeScript could resolve the value to something numeric). Practically speaking, what this means is that string enum members are only ever compatible with other string enums of the same value.

For more information, see the pull request that introduced this change .

Name Restrictions on Enum Members

TypeScript no longer allows enum members to use the names Infinity , -Infinity , or NaN .

See more details here .

Better Mapped Type Preservation Over Tuples with any Rest Elements

Previously, applying a mapped type with any into a tuple would create an any element type. This is undesirable and is now fixed.

For more information, see the fix along with the follow-on discussion around behavioral changes and further tweaks .

Emit Changes

While not a breaking change per-se, developers may have implicitly taken dependencies on TypeScript’s JavaScript or declaration emit outputs. The following are notable changes.

  • Preserve type parameter names more often when shadowed
  • Move complex parameter lists of async function into downlevel generator body
  • Do not remove binding alias in function declarations
  • ImportAttributes should go through the same emit phases when in an ImportTypeNode

What’s Next?

In the coming months, we’ll be working on TypeScript 5.5, and you can see our iteration plan available on GitHub . Our target release dates are public so you, your team, and the broader TypeScript community can schedule accordingly. You can also try out nightly releases on npm or use the latest version of TypeScript and JavaScript in Visual Studio Code .

But until then, TypeScript 5.4 is still the latest and greatest stable version, and we hope that it makes coding a joy for you!

Happy Hacking!

– Daniel Rosenwasser and the TypeScript Team

javascript conditional assignment undefined

Daniel Rosenwasser Senior Program Manager, TypeScript

javascript conditional assignment undefined

Leave a comment Cancel reply

Log in to start the discussion.

light-theme-icon

Insert/edit link

Enter the destination URL

Or link to existing content

IMAGES

  1. How to Check if a Variable is Undefined in Javascript · Dev Practical

    javascript conditional assignment undefined

  2. JavaScript undefined

    javascript conditional assignment undefined

  3. [Solved] javascript: is this a conditional assignment?

    javascript conditional assignment undefined

  4. What is a Conditional Statement in JavaScript or a Desicion Statement?

    javascript conditional assignment undefined

  5. Javascript #3

    javascript conditional assignment undefined

  6. JavaScript Conditional Statements Tutorial with Example

    javascript conditional assignment undefined

VIDEO

  1. Lecture 1 of JS (Introduction of JS, variables, and datatypes)

  2. Programs of javascript using conditional statements

  3. JavaScript conditional statement 21-05-2023

  4. JavaScript Conditional Statement if,else and else if✅

  5. JavaScript

  6. Web development

COMMENTS

  1. Best Way for Conditional Variable Assignment

    1st method if (true) { var myVariable = 'True'; } else { var myVariable = 'False'; } 2nd Method var myVariable = 'False'; if (true) { myVariable = 'True'; } I actually prefer 2nd one without any specific technical reason. What do you guys think? javascript Share Improve this question Follow edited Nov 11, 2019 at 20:57 Emile Bergeron

  2. Nullish coalescing operator (??)

    The nullish coalescing ( ??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. Try it Syntax js leftExpr ?? rightExpr Description

  3. Logical OR assignment (||=)

    Description Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: js

  4. Expressions and operators

    The shorthand assignment operator += can also be used to concatenate strings. For example, var mystring = 'alpha'; mystring += 'bet'; // evaluates to "alphabet" and assigns this value to mystring. Conditional (ternary) operator. The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two ...

  5. 7 Tips to Handle undefined in JavaScript

    1. What is undefined JavaScript has 6 primitive types: Boolean: true or false Number: 1, 6.7, 0xFF String: "Gorilla and banana" Symbol: Symbol ("name") (starting ES2015) Null: null Undefined: undefined. And a separated object type: {name: "Dmitri"}, ["apple", "orange"].

  6. if...else

    Description Multiple if...else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in JavaScript. if ( condition1 ) statement1 else if ( condition2 ) statement2 else if ( condition3 ) statement3 ... else statementN

  7. Javascript undefined condition

    6 Could somebody explain to me the difference between if (obj.x == undefined) and if (typeof obj.x == 'undefined') In some context the first one works fine, but in other I need to use the second way. Questions 1 - What is the difference between the two condition? 2 - Is there a best practice? javascript Share Improve this question Follow

  8. Nullish coalescing operator

    The nullish coalescing operator is written as two question marks ??.. As it treats null and undefined similarly, we'll use a special term here, in this article. For brevity, we'll say that a value is "defined" when it's neither null nor undefined.. The result of a ?? b is:. if a is defined, then a,; if a isn't defined, then b.; In other words, ?? returns the first argument if it ...

  9. Conditional (ternary) operator

    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (? ), then an expression to execute if the condition is truthy followed by a colon (: ), and finally the expression to execute if the condition is falsy .

  10. Advanced JavaScript Operators

    In this article, I'm going to teach you how to use three advanced JavaScript operators: the Nullish Coalescing, Optional Chaining, and Destructuring Assignment operators. These three operators will help you write clearer and less error-prone code. The Nullish Coalescing Operator When you're inspecting JavaScript code, you may.

  11. Destructuring assignment

    The ( ..) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration. {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal. However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2} NOTE: Your ( ..) expression needs to be ...

  12. Optional chaining

    Summary. The optional chaining ?. syntax has three forms:. obj?.prop - returns obj.prop if obj exists, otherwise undefined.; obj?.[prop] - returns obj[prop] if obj exists, otherwise undefined. obj.method?.() - calls obj.method() if obj.method exists, otherwise returns undefined. As we can see, all of them are straightforward and simple to use. The ?. checks the left part for null ...

  13. javascript

    ... aThing = possiblyNull?.thing This will be roughly like: if (possiblyNull != null) aThing = possiblyNull.thing Ideally the solution should not assign (even undefined) to aThing if possiblyNull is null javascript coffeescript ecmascript-6 babeljs Share Improve this question edited Jan 31, 2017 at 23:30 asked Aug 21, 2015 at 11:23 P Varga

  14. Conditional (ternary) Operator

    The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement. Syntax condition ? expr1 : expr2 Parameters condition (or conditions) An expression that evaluates to true or false. expr1, expr2 Expressions with values of any type. Description

  15. In JavaScript, how to conditionally add a member to an object?

    var a = {}; if (someCondition) a.b = 5; Now, I would like to write a more idiomatic code. I am trying: a = { b: (someCondition? 5 : undefined) }; But now, b is a member of a whose value is undefined. This is not the desired result. Is there a handy solution? Update I seek for a solution that could handle the general case with several members. a = {

  16. JavaScript Check if Undefined

    When a variable is declared or initialized but no value is assigned to it, JavaScript automatically displays "undefined". It looks like this: let myStr; console.log(myStr); // undefined Also, when you try accessing values in, for example, an array or object that doesn't exist, it will throw undefined. let user = { name: "John Doe", age: 14 };

  17. if...else

    js if (condition) statement1 // With an else clause if (condition)

  18. Announcing TypeScript 5.4

    In fact, if you've been writing JavaScript in either of those editors, you've been using TypeScript all this time! To get started using TypeScript through NuGet or through npm with the following command: npm install -D typescript Here's a quick list of what's new in TypeScript 5.4! Preserved Narrowing in Closures Following Last Assignments

  19. How do you use the ? : (conditional) operator in JavaScript?

    1 possible duplicate of javascript if alternative - Rob Hruska Jun 7, 2011 at 2:35 Add a comment 20 Answers Sorted by: 765 This is a one-line shorthand for an if-else statement. It's called the conditional operator. 1 Here is an example of code that could be shortened with the conditional operator: var userType; if (userIsYoungerThan18) {

  20. Optional chaining (?.)

    js const temp = obj.first; const nestedProp = temp === null || temp === undefined ? undefined : temp.second; Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value undefined. js undeclaredVar?.prop; // ReferenceError: undeclaredVar is not defined Optional chaining with function calls

  21. Expressions and operators

    This chapter documents all the JavaScript language operators, expressions and keywords. Expressions and operators by category For an alphabetical listing see the sidebar on the left. Primary expressions Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ). this

  22. Destructuring assignment

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Try it Syntax js