Several mistakes that JavaScript beginners often make

Several mistakes that JavaScript beginners often make

Preface

Putting aside the problems with the JavaScript language design, after all, it was designed by Brendan Eich in just ten days, so it is inevitable that it has some flaws. As developers, how can we avoid some common low-level mistakes? This article lists several common mistakes and see if you find them familiar.

Confusing undefined and null

Both undefined and null in JavaScript can be used to represent the absence of a value, but there is a difference between the two. undefined literally means "undefined", but its meaning actually goes beyond the scope of undefined variables: trying to read a non-existent property of an object, the return value of a function without a return statement, a variable that is not assigned a value after declaration, or even a variable that is explicitly assigned to undefined, all result in undefined. Testing its type with typeof yields the string 'undefined'. Null is more pure, and the variable only has this value when it is set to null. In addition, null is an object type, that is, the value of typeof(null) is the string 'object'.

It should be noted that when using if to judge that both values ​​are false, null==undefined is true, which is often confusing for beginners. Therefore, try to set all "no value" to undefined, which saves the trouble of judgment and distinction.

Functions that return undefined:

const f = () => {}

Set the value of a variable to undefined:

x = undefined;

Determine whether the property is undefined:

typeof obj.prop === 'undefined'
obj.prop === undefined

Determine whether a variable is undefined:

typeof x === 'undefined'

If a variable is declared but no value is assigned, it will automatically have the value undefined.

If you must judge null, use the same judgment:

obj.prop === null
x === null

Using typeof, you cannot judge null because it is an object type.

Confusing number addition and string concatenation

In JavaScript, the + operator can be used for both number addition and string concatenation. Since JavaScript is a dynamic language, operators will automatically convert variables to the same data type before performing operations. for example:

let x = 1 + 1; // 2

The result is 2, which is what we expect from a numeric addition operation, since both values ​​are numbers.

However, if the expression is:

let x = 1 + '1'; // "11"

The result is '11' because the first digit is converted to a string. Here the + operator is used for string concatenation, not numeric addition. Here we can directly see the value of the expression which is relatively clear. If the expression is composed of multiple variables, it is difficult to determine the type.

To solve this problem, we can convert all strings into numeric types and then perform calculations. For example:

let x = 1;  
let y = '2';  
let z = Number(x) + Number(y);

In this way, the running result is 3. The Number function accepts a value of any type and returns a number if it can be converted to a number, otherwise it returns NaN. You can also use the new Number(...).valueOf() function:

let x = 1;  
let y = '2';  
let z = new Number(x).valueOf() + new Number(y).valueOf();

Since new Number(...) instantiates a constructor, it returns an object, not a numeric type. If you want to get the original numeric type, you need to use the valueOf method of the object. There is actually a simpler way:

let x = 1;  
let y = '2';  
let z = +x + +y;

The + in front of a variable converts it to a number, or NaN, the same as the Number function.

Return statement line break problem

JavaScript syntax specifies that a newline signifies the end of a statement. For example:

const add = (a, b) => {  
  return  
  a + b;  
}
add(1,2); // undefined

I thought it would return 3, but it actually returned undefined. This is because the function has already executed return before a + b. There are two ways to solve this problem: either put the expression and return on the same line, or put the expression in parentheses.

const add = (a, b) => {  
  return a + b;  
}
// or const add = (a, b) => {  
  return (  
    a + b  
  );  
}

Why can brackets be used to wrap lines? Because the words in parentheses are expressions, not statements. Expressions can be split over multiple lines if they are long. Using arrow functions would be more intuitive:

const add = (a, b) => a + b

The single-line expression in the arrow function has a return effect. Of course, you can also put a layer of parentheses around the expression:

const add = (a, b) => (a + b)

This bracket is somewhat useful in arrow functions that return object literals, because without the parentheses (), {} is just the start and end markers of the function body. To return an object literal, you must explicitly return {...}.

If a statement in a line of code is incomplete, the JavaScript parser will merge the statements in the next line together for parsing. for example:

const power = (a) => {  
  const  
    power = 10;  
  return a ** 10;  
}
// is equivalent to:
const power = (a) => {  
  const power = 10;  
  return a ** 10;  
}

However, for complete statements, such as return, multiple lines will not be merged.

Using return to break out of forEach loop

JavaScript arrays have a forEach method that is used to loop over array elements. Beginners can easily think of the break or continue keyword in the for loop, which is used to terminate the loop. But sorry, forEach does not have these two keywords. Then can we use return? It can be used, but its function is to return the function early, which is similar to the effect of continue and is used to end the current loop. To jump out of the entire loop, return cannot do it.

const nums = [1, 2, 3, 4, 5, 6];
let firstEven;
nums.forEach(n => {
  if (n % 2 === 0 ) {
    firstEven = n;
    return n;
  }
});
console.log(firstEven); // 6

The original intention of the code is to find the first even number and exit the loop when it is found. But the loop is not actually exited, so the final result is the last even number.
Is there a solution? In this case, you can use a for loop, or use array filter, find and other methods.

Summarize

Although JavaScript is easy to learn, it is still easy to make mistakes if you are not careful. This article briefly introduces several common mistakes, I hope it will be helpful to you.

The above are the details of several mistakes that JavaScript beginners often make. For more information about JS, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript encapsulates DOM event handlers as event.js, resulting in low-level errors
  • The accumulation of low-level errors that novices often encounter during the Extjs learning process
  • 7 native JS error types you should know
  • Detailed explanation of JavaScript error capture
  • JavaScript statement error throw, try and catch example analysis
  • Detailed explanation of common JS errors and solutions
  • JS error handling and debugging operation example analysis
  • JavaScript beginner tutorial and simple implementation of Gobang applet
  • JavaScript beginners must read "new"

<<:  Solve the problem that ifconfig and addr cannot see the IP address in Linux

>>:  Introduction to new features of MySQL 8.0.11

Recommend

How to install a virtual machine with Windows services on Mac

1. Download the virtual machine Official download...

Summary of the application of transition components in Vue projects

​Transtion in vue is an animation transition enca...

Windows Server 2019 IIS10.0+PHP(FastCGI)+MySQL Environment Construction Tutorial

Preparation 1. Environmental Description: Operati...

Detailed explanation of three ways to connect Docker containers to each other

There are three ways to interconnect and communic...

Parse CSS to extract image theme color function (tips)

background It all started when a classmate in the...

How to use CSS to display multiple images horizontally in the center

Let me first talk about the implementation steps:...

In-depth explanation of MySQL stored procedures (in, out, inout)

1. Introduction It has been supported since versi...

Stop using absolute equality operators everywhere in JS

Table of contents Overview 1. Test for null value...

Zabbix implements monitoring of multiple mysql processes

Three MySQL instance processes are started on one...

MySQL view introduction and basic operation tutorial

Preface View is a very useful database object in ...

A brief discussion on creating cluster in nodejs

Table of contents cluster Cluster Details Events ...

MySQL slow query log configuration and usage tutorial

Preface MySQL slow query log is a function that w...

Example analysis of MySQL startup and connection methods

Table of contents How to start mysqld Method 1: m...

How to configure the same domain name for the front and back ends of nginx

This article mainly introduces the method of conf...