Usage of ?. and ?? in JavaScript

1.?. (optional chain operator)

In JavaScript, "?." is a new operator called "Optional Chaining". It allows us to avoid errors when accessing a property that may be null or undefined or calling a method that may not exist.
Use the ?.operator to safely access an object's properties and methods without causing an error and causing the program to stop execution. When the object's property or method does not exist, the expression returns undefined instead of throwing a TypeError exception.

1.1 Access object properties

	const person = {
    
    
	  name: 'John',
	  address: {
    
    
	    city: 'New York'
	  }
	};

	console.log(person.address?.city); // 输出:'New York'
	
	// 输出:undefined,因为person对象没有age属性
	console.log(person.age?.toString()); 

1.2 Calling object methods

	const calculator = {
    
    
	  add: function(a, b) {
    
    
	    return a + b;
	  }
	};
	
	console.log(calculator.add?.(2, 3)); // 输出:5
	
	// 输出:undefined,因为calculator对象没有subtract方法
	console.log(calculator.subtract?.(5, 2)); 

1.3 Chain usage?.

	const user = {
    
    
	  profile: {
    
    
	    name: 'Alice',
	    email: '[email protected]'
	  }
	};
	
	console.log(user?.profile?.name); // 输出:'Alice'
	
	// 输出:undefined,因为user对象没有address属性
	console.log(user?.address?.city); 

Precautions:

  • When using the ?. operator, if the target property or method exists and is callable, they will execute normally.
  • If the target is null or undefined, the expression returns undefined immediately and no further attempts are made to access subsequent properties or methods.
  • The operator cannot be used with [] (square brackets). For example: obj?.[index] is invalid syntax.

2. ?? (null value coalescing operator)

In JavaScript, "??" is the usage of the null value coalescing operator. It is used to determine whether an expression is null or undefined and returns a default value.

	const name = null; 
	/*
	  使用??运算符来判断name的值是否为空,如果为空,则赋予默认值"Unknown"
	*/
	const displayName = name ??  "Unknown"; 
	
	console.log(displayName); // 输出: Unknown

	/*
	  经常在表格或者数据渲染时可以用到,当表格数据为空时,直接显示 - 
	  const data = null?? '-'
	  
	*/

Guess you like

Origin blog.csdn.net/weixin_56733569/article/details/132021969