Cannot Read Property Match of Undefined Nom

Most of the modern languages like Ruby, Python, or Coffee have a unmarried null value (nil or null), which seems a reasonable arroyo.

But JavaScript is different.

null, just also undefined, represent in JavaScript empty values. So what's the verbal departure between them?

The short reply is that JavaScript interpreter returns undefined when accessing a variable or object holding that is not even so initialized. For instance:

          

javascript

let company ;

company ; // => undefined

let person = { name: 'John Smith' };

person . age ; // => undefined

On the other side, null represents a missing object reference. JavaScript doesn't initialize variables or object properties with null.

Some native methods like Cord.prototype.match() can render null to announce a missing object. Take a look at the sample:

          

javascript

let array = null ;

assortment ; // => null

let motion picture = { name: 'Starship Troopers' , musicBy: aught };

moving-picture show . musicBy ; // => cypher

'abc' . friction match ( / [ 0-9 ] / ); // => null

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

Often such risky actions generate undefined related errors:

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

JavaScript developer can understand the irony of this joke:

          

javascript

function undefined () {

// problem solved

}

To reduce such errors, you take to empathise the cases when undefined is generated. Let'due south explore undefined and its effect on code condom.

Table of Contents

  • 1. What is undefined
  • 2. Scenarios that create undefined
    • 2.one Uninitialized variable
    • ii.2 Accessing a non-existing belongings
    • 2.3 Function parameters
    • 2.four Function render value
    • 2.5 void operator
  • three. undefined in arrays
  • 4. Departure between undefined and cipher
  • 5. Decision

1. What is undefined

JavaScript has 6 archaic types:

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

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

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 non been assigned a value.

The standard conspicuously defines that yous volition receive undefined when accessing uninitialized variables, not-existing object properties, non-existing assortment elements, and akin.

A few examples:

          

javascript

allow number ;

number ; // => undefined

let movie = { name: 'Interstellar' };

film . yr ; // => undefined

let movies = [ 'Interstellar' , 'Alexander' ];

movies [ 3 ]; // => undefined

The above example demonstrates that accessing:

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

are evaluated to 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' cord for an undefined value:

          

javascript

typeof undefined === 'undefined' ; // => truthful

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

          

javascript

let zero ;

typeof cipher === 'undefined' ; // => truthful

2. Scenarios that create undefined

2.1 Uninitialized variable

A alleged variable simply not yet assigned with a value (uninitialized) is by default undefined.

Obviously and simple:

          

javascript

let myVariable ;

myVariable ; // => undefined

myVariable is alleged and non however assigned with a value. Accessing the variable evaluates to undefined.

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

Ideally, you would assign a value correct away after proclamation const myVariable = 'Initial value'. But that's non always possible.

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

In my opinion, one of the best features of ECMAScript 2015 is the new way to declare variables using const and permit. Information technology is a big step forrad.

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

I recommend const variable when its value is not going to alter. It creates an immutable bounden.

1 of the nice features of const is that yous 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.

Allow'south check the function that verifies whether a give-and-take is a palindrome:

          

javascript

role isPalindrome ( discussion ) {

const length = word . length ;

const half = Math . floor ( length / 2 );

for ( let alphabetize = 0 ; alphabetize < half ; index ++) {

if ( word [ alphabetize ] !== word [ length - alphabetize - one ]) {

return false ;

}

}

return truthful ;

}

isPalindrome ( 'madam' ); // => true

isPalindrome ( 'howdy' ); // => fake

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

Use let announcement for variables whose value tin can change. Whenever possible assign an initial value correct abroad, e.1000. allow index = 0.

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

Do not write var, write const and let in JavaScript

var declaration trouble is the variable hoisting within the function scope. Yous can declare a var variable somewhere at the finish of the function scope, simply still, you can access information technology before declaration: and you'll become an undefined.

          

javascript

role bigFunction () {

// lawmaking...

myVariable ; // => undefined

// lawmaking...

var myVariable = 'Initial value' ;

// code...

myVariable ; // => 'Initial value'

}

bigFunction ();

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

Contrary, a const or let variable cannot be accessed before the declaration line — the variable is in a temporal expressionless zone before the announcement. And that'south nice because you take less run a risk to access an undefined.

The above instance updated with permit (instead of var) throws a ReferenceError because the variable in the temporal expressionless zone is not accessible.

          

javascript

office bigFunction () {

// code...

myVariable ; // => Throws 'ReferenceError: myVariable is not defined'

// code...

allow myVariable = 'Initial value' ;

// code...

myVariable ; // => 'Initial value'

}

bigFunction ();

Encouraging the usage of const for immutable bindings or let otherwise ensures a practise 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 tin can exist loftier or low.

A high cohesion module is preferable considering the elements of such a module focus solely on a single task. Information technology 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, information technology makes the module easier to reuse
  • Testable: you would easier examination a module that'south focused on a single chore

Components coupling and cohesion

High cohesion accompanied by loose coupling is the feature of a well-designed arrangement.

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

For example, if a variable solely exists to form the logic of cake scope, and then declare and make the variable alive only inside that block (using const or let declarations). Practice not expose this variable to the outer cake scope, since the outer cake shouldn't care about this variable.

I archetype instance of the unnecessarily extended life of variables is the usage of for cycle inside a function:

          

javascript

part someFunc ( assortment ) {

var index , item , length = array . length ;

// some code...

// some lawmaking...

for ( index = 0 ; index < length ; index ++) {

item = assortment [ index ];

// some lawmaking...

}

render 'some result' ;

}

index, item and length variables are alleged at the beginning of the function body. Still, they are used simply near the stop. What's the problem with this arroyo?

Between the declaration at the superlative and the usage in for statement the variables index, item are uninitialized and exposed to undefined. They have an unreasonably long lifecycle in the unabridged office telescopic.

A better arroyo is to movement these variables equally close equally possible to their usage place:

          

javascript

office someFunc ( assortment ) {

// some code...

// some lawmaking...

const length = assortment . length ;

for ( let index = 0 ; index < length ; alphabetize ++) {

const particular = array [ index ];

// some

}

return 'some event' ;

}

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

Why is the modified version better than the initial one? Let's meet:

  • The variables are not exposed to uninitialized country, thus you have no run a risk of accessing undefined
  • Moving the variables equally shut every bit possible to their usage place increases the code readability
  • High cohesive chunks of code are easier to refactor and extract into dissever functions, if necessary

2.2 Accessing a non-existing property

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

Allow'due south demonstrate that in an example:

          

javascript

allow favoriteMovie = {

title: 'Blade Runner'

};

favoriteMovie . actors ; // => undefined

favoriteMovie is an object with a unmarried belongings championship. Accessing a not-existing property actors using a belongings accessor favoriteMovie.actors evaluates to undefined.

Accessing a not-existing property does non throw an error. The problem appears when trying to get information from the non-existing property, which is the most common undefined trap, reflected in the well-known error bulletin TypeError: Cannot read holding <prop> of undefined.

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

          

javascript

let favoriteMovie = {

title: 'Blade Runner'

};

favoriteMovie . actors [ 0 ];

// TypeError: Cannot read holding '0' of undefined

favoriteMovie does non take the property actors, so favoriteMovie.actors evaluates to undefined.

As a result, accessing the first particular of an undefined value using the expression favoriteMovie.actors[0] throws a TypeError.

The permissive nature of JavaScript that allows accessing non-existing properties is a source of nondeterminism: the property may be set or not. The skillful way to bypass this trouble is to restrict the object to have always divers the properties that information technology holds.

Unfortunately, often y'all don't have command over the objects. Such objects may have a different set of properties in various scenarios. And so you have to handle all these scenarios manually.

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

  • first: element inserted at the kickoff of array
  • last: element inserted at the terminate of array.

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

The first version of suspend(), a flake naive, may look like this:

          

javascript

function append ( array , toAppend ) {

const arrayCopy = [... array ];

if ( toAppend . start ) {

arrayCopy . unshift ( toAppend . commencement );

}

if ( toAppend . terminal ) {

arrayCopy . push ( toAppend . final );

}

return arrayCopy ;

}

append ([ 2 , 3 , 4 ], { offset: 1 , last: 5 }); // => [1, ii, 3, 4, v]

append ([ 'Hello' ], { final: 'World' }); // => ['Hello', 'World']

suspend ([ viii , xvi ], { get-go: four }); // => [iv, viii, 16]

Considering toAppend object can omit offset or terminal properties, it is obligatory to verify whether these backdrop be in toAppend.

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

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

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

          

javascript

append ([ 10 ], { first: 0 , last: false }); // => [10]

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

The tips that follow explicate how to correctly check the holding's existence.

Tip iii: Check the holding existence

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

  • obj.prop !== undefined: compare confronting undefined direct
  • typeof obj.prop !== 'undefined': verify the property value blazon
  • obj.hasOwnProperty('prop'): verify whether the object has an own property
  • 'prop' in obj: verify whether the object has an ain or inherited property

My recommendation is to utilise in operator. Information technology has a brusque and sugariness syntax. in operator presence suggests a clear intent of checking whether an object has a specific holding, without accessing the actual property value.

Do not write var, write const and let in JavaScript

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

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

          

javascript

function suspend ( array , toAppend ) {

const arrayCopy = array . slice ();

if ( 'kickoff' in toAppend ) {

arrayCopy . unshift ( toAppend . commencement );

}

if ( 'last' in toAppend ) {

arrayCopy . push ( toAppend . final );

}

render arrayCopy ;

}

append ([ 2 , iii , 4 ], { starting time: 1 , concluding: 5 }); // => [1, 2, 3, iv, v]

append ([ 10 ], { first: 0 , final: false }); // => [0, x, fake]

'beginning' in toAppend (and 'last' in toAppend) is true whether the corresponding property exists, false otherwise.

in operator fixes the trouble with inserting falsy elements 0 and fake. Now, adding these elements at the get-go and the finish of [10] produces the expected upshot [0, 10, false].

Tip 4: Destructuring to access object backdrop

When accessing an object property, sometimes information technology'southward necessary to set a default value if the property does not be.

You might use in accompanied with ternary operator to attain that:

          

javascript

const object = { };

const prop = 'prop' in object ? object . prop : 'default' ;

prop ; // => 'default'

Ternary operator syntax becomes daunting when the number of properties to bank check increases. For each property, y'all 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, permit's go familiar with a great ES2015 feature called object destructuring.

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

Indeed, the property extraction is now precise:

          

javascript

const object = { };

const { prop = 'default' } = object ;

prop ; // => 'default'

To come across things in action, let's define a useful part that wraps a string in quotes.

quote(subject, config) accepts the first argument every bit the string to exist 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 the object destructuring, let'due south implement quote():

          

javascript

function quote ( str , config ) {

const { char = '"' , skipIfQuoted = truthful } = config ;

const length = str . length ;

if ( skipIfQuoted

&& str [ 0 ] === char

&& str [ length - one ] === char ) {

return str ;

}

return char + str + char ;

}

quote ( 'Hullo World' , { char: '*' }); // => '*Hello World*'

quote ( '"Welcome"' , { skipIfQuoted: true }); // => '"Welcome"'

const { char = '"', skipIfQuoted = truthful } = 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 nevertheless has room for improvement.

Let'south move the destructuring assignment into the parameters section. And fix a default value (an empty object { }) for the config parameter, to skip the second statement when default settings are plenty.

          

javascript

role quote ( str , { char = '"' , skipIfQuoted = true } = {}) {

const length = str . length ;

if ( skipIfQuoted

&& str [ 0 ] === char

&& str [ length - 1 ] === char ) {

render str ;

}

return char + str + char ;

}

quote ( 'Hello World' , { char: '*' }); // => '*Hullo World*'

quote ( 'Sunny solar day' ); // => '"Sunny day"'

The destructuring assignment replaces the config parameter in the role'southward 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 2d argument is non specified at all quote('Sunny day').

Object destructuring is a powerful characteristic that handles efficiently the extraction of backdrop from objects. I like the possibility to specify a default value to be returned when the accessed property doesn't exist. Every bit a result, yous avoid undefined and the hassle around information technology.

Tip 5: Fill the object with default properties

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

The ES2015 Object.assign(target, source1, source2, ...) copies the values of all enumerable ain properties from ane or more source objects into the target object. The role returns the target object.

For instance, yous need to admission the backdrop of unsafeOptions object that doesn't always contain its full ready of properties.

To avoid undefined when accessing a non-existing property from unsafeOptions, let'southward brand 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 backdrop from unsafeOptions, but the missing ones are taken from defaults.
          

javascript

const unsafeOptions = {

fontSize: eighteen

};

const defaults = {

fontSize: 16 ,

color: 'blackness'

};

const options = Object . assign ({}, defaults , unsafeOptions );

options . fontSize ; // => xviii

options . color ; // => 'black'

unsafeOptions contains only fontSize holding. defaults object defines the default values for backdrop fontSize and color.

Object.assign() takes the start statement equally a target object {}. The target object receives the value of fontSize property from unsafeOptions source object. And the value of color holding from defaults source object, because unsafeOptions doesn't comprise color.

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

You lot are now safe to access whatsoever holding of options object, including options.colour that wasn't available in unsafeOptions initially.

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

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

          

javascript

const unsafeOptions = {

fontSize: 18

};

const defaults = {

fontSize: xvi ,

color: 'black'

};

const options = {

... defaults ,

... unsafeOptions

};

options . fontSize ; // => 18

options . color ; // => 'blackness'

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

Filling an incomplete object with default property values is an efficient strategy to make your code condom and durable. No matter the situation, the object ever 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:

          

javascript

const value = nullOrUndefinedValue ?? defaultValue ;

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

          

javascript

const styles = {

fontSize: 18

};

styles . color ?? 'black' ; // => 'black'

styles . fontSize ?? 16 ; // => xviii

styles object doesn't accept the property colour, 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.iii Function parameters

The role parameters implicitly default to undefined.

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

          

javascript

office multiply ( a , b ) {

a ; // => 5

b ; // => three

return a * b ;

}

multiply ( 5 , three ); // => 15

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

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

Allow's slightly modify the previous example by calling the role with just one argument:

          

javascript

function multiply ( a , b ) {

a ; // => 5

b ; // => undefined

render a * b ;

}

multiply ( five ); // => NaN

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

Tip half dozen: Employ default parameter value

Sometimes a function does not require the full gear up 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 information technology to 2:

          

javascript

function multiply ( a , b ) {

if ( b === undefined ) {

b = 2 ;

}

a ; // => 5

b ; // => two

return a * b ;

}

multiply ( five ); // => 10

The function is invoked with a single statement multiply(v). Initially, a parameter is 2 and b is undefined.
The conditional statement verifies whether b is undefined. If information technology 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 improve approach is to use the ES2015 default parameters feature. It'southward short, expressive and no directly comparisons with undefined.

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

          

javascript

function multiply ( a , b = two ) {

a ; // => v

b ; // => two

return a * b ;

}

multiply ( 5 ); // => x

multiply ( 5 , undefined ); // => ten

b = ii in the office signature makes certain that if b is undefined, the parameter defaults to ii.

ES2015 default parameters characteristic is intuitive and expressive. Always use it to set default values for optional parameters.

2.iv Role return value

Implicitly, without render statement, a JavaScript role returns undefined.

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

          

javascript

function square ( x ) {

const res = x * x ;

}

square ( ii ); // => undefined

foursquare() function does non return any computation results. The function invocation result is undefined.

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

          

javascript

role square ( x ) {

const res = x * 10 ;

return ;

}

square ( 2 ); // => undefined

return; statement is executed, but it doesn't render any expression. The invocation effect is too undefined.

Of course, indicating well-nigh return the expression to be returned works as expected:

          

javascript

role square ( x ) {

const res = x * x ;

return res ;

}

foursquare ( 2 ); // => 4

At present the function invocation is evaluated to iv, which is 2 squared.

Tip 7: Don't trust the automatic semicolon insertion

The post-obit list of statements in JavaScript must terminate with semicolons (;):

  • empty statement
  • permit, const, var, import, export declarations
  • expression statement
  • debugger argument
  • proceed statement, break argument
  • throw statement
  • render statement

If you use one of the in a higher place statements, be certain to indicate a semicolon at the end:

          

javascript

role getNum () {

// Notice the semicolons at the cease

let num = 1 ;

return num ;

}

getNum (); // => 1

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 state of affairs ECMAScript provides an Automatic Semicolon Insertion (ASI) machinery, which inserts for yous the missing semicolons.

Helped by ASI, y'all can remove the semicolons from the previous instance:

          

javascript

part getNum () {

// Notice that semicolons are missing

let num = 1

return num

}

getNum () // => 1

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

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

In that location is one small, but annoying trap created by ASI. When a newline stands between render and the returned expression return \northward expression, ASI automatically inserts a semicolon before the newline return; \northward expression.

What it does mean inside a function to take render; statement? The part returns undefined. If yous don't know in detail the machinery of ASI, the unexpectedly returned undefined is misleading.

For case, let'due south study the returned value of getPrimeNumbers() invocation:

          

javascript

function getPrimeNumbers () {

return

[ 2 , 3 , five , 7 , 11 , 13 , 17 ]

}

getPrimeNumbers () // => undefined

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

          

javascript

role getPrimeNumbers () {

return ;

[ 2 , 3 , v , 7 , xi , xiii , 17 ];

}

getPrimeNumbers (); // => undefined

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

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

          

javascript

part getPrimeNumbers () {

render [

2 , iii , 5 , 7 , 11 , xiii , 17

];

}

getPrimeNumbers (); // => [ii, 3, five, vii, 11, thirteen, 17]

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

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

ii.5 void operator

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

          

javascript

void 1 ; // => undefined

void ( simulated ); // => undefined

void {name: 'John Smith' }; // => undefined

void Math . min ( i , 3 ); // => undefined

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

3. undefined in arrays

You get undefined when accessing an assortment element with an out of bounds alphabetize.

          

javascript

const colors = [ 'blue' , 'white' , 'blood-red' ];

colors [ v ]; // => undefined

colors [- 1 ]; // => undefined

colors array has three elements, thus valid indexes are 0, i, and 2.

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

In JavaScript, y'all might run across so-called sparse arrays. Theses are arrays that take gaps, i.due east. at some indexes, no elements are divers.

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

The following case generates sparse arrays and tries to admission their empty slots:

          

javascript

const sparse1 = new Assortment ( 3 );

sparse1 ; // => [<empty slot>, <empty slot>, <empty slot>]

sparse1 [ 0 ]; // => undefined

sparse1 [ 1 ]; // => undefined

const sparse2 = [ 'white' , , 'blueish' ]

sparse2 ; // => ['white', <empty slot>, 'bluish']

sparse2 [ 1 ]; // => undefined

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

sparse2 is created with an assortment literal with the missing 2nd 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 forestall the cosmos of thin arrays.

four. Divergence between undefined and nada

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

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

Allow's explore the difference in some examples.

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

          

javascript

let number ;

number ; // => undefined

number variable is undefined, which indicates an uninitialized variable.

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

          

javascript

const obj = { firstName: 'Dmitri' };

obj . lastName ; // => undefined

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

On the other side, you know that a variable expects an object. Merely for some reason, y'all can't instantiate the object. In such case zilch 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:

          

javascript

function clone ( obj ) {

if ( typeof obj === 'object' && obj !== null ) {

return Object . assign ({}, obj );

}

return zip ;

}

clone ({ proper name: 'John' }); // => {name: 'John'}

clone ( 15 ); // => null

clone ( null ); // => null

However clone() might be invoked with a not-object statement: 15 or null. In such a case, the function cannot create a clone, and so it returns null — the indicator of a missing object.

typeof operator makes the distinction between undefined and nada:

          

javascript

typeof undefined ; // => 'undefined'

typeof nada ; // => 'object'

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

          

javascript

allow nothing = undefined ;

let missingObject = null ;

nothing === missingObject ; // => false

5. Conclusion

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 premises indexes to access array elements
  • the invocation issue of a office that returns nothing

Comparing straight against undefined is unsafe because yous rely on a permitted but discouraged practice mentioned in a higher place.

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

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

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

wilsonworning.blogspot.com

Source: https://dmitripavlutin.com/7-tips-to-handle-undefined-in-javascript/

0 Response to "Cannot Read Property Match of Undefined Nom"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel