search
HomeWeb Front-endJS TutorialIntroduction to operators and expressions in JavaScript

This article brings you an introduction to operators and expressions in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Unary operator

1.delete operator

The delete operator is used to delete an attribute of an object; if there is no reference to this attribute, then it It will eventually be released

Syntax: delete expression

The delete operator will remove the specified attribute from an object. Returns true when deleted successfully, otherwise returns false

   let Employee = {
        age: 28,
        name: 'abc',
        designation: 'developer'
    };
    console.log(delete Employee.name);   // returns true
    console.log(delete Employee.age);    // returns true
    console.log(Employee); //{designation: "developer"}

2.typeof operator

The typeof operator returns a string indicating the type of the uncalculated operand

Syntax: typeof operand; typeof (operand);

    typeof NaN === 'number';
    typeof Number(1) === 'number';
    typeof "" === 'string';
    typeof true === 'boolean';
    typeof Symbol('foo') === 'symbol';
    typeof undefined === 'undefined';
    typeof null === 'object'
    typeof [1, 2, 4] === 'object';
    typeof new Boolean(true) === 'object';
    typeof new Number(1) === 'object';
    typeof new String("abc") === 'object';
    typeof function(){} === 'function';

3.void operator

The void operator evaluates the given expression and returns undefined

Syntax: void expression

<a>
  这个链接点击之后不会做任何事情,如果去掉 void(),
  点击之后整个页面会被替换成一个字符 0。
</a>
<p> chrome中即使<a>也没变化,firefox中会变成一个字符串0 </a></p>
<a>
  点击这个链接会让页面背景变成绿色。
</a>

2. Relational operators

1.in operator

If the specified attribute is in the specified object or its prototype chain, then in operator returns true

Syntax: prop in object

    let trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    console.log(0 in trees); // 返回true
    console.log(3 in trees); // 返回true
    console.log(6 in trees); // 返回false
    console.log("bay" in trees); // 返回false (必须使用索引号,而不是数组元素的值)
    console.log("length" in trees); // 返回true (length是一个数组属性)

2.instanceof operator

instanceof operator is used to test whether an object exists in its prototype chain The prototype attribute of the constructor

Syntax: object instanceof constructor

    let simpleStr = "This is a simple string";
    let myString  = new String();
    let newStr    = new String("String created with constructor");
    let myDate    = new Date();
    let myObj     = {};
    simpleStr instanceof String; // 返回 false, 检查原型链会找到 undefined
    myString  instanceof String; // 返回 true
    newStr    instanceof String; // 返回 true
    myString  instanceof Object; // 返回 true
    myDate instanceof Date;     // 返回 true
    myObj instanceof Object;    // 返回 true, 尽管原型没有定义

3. Expression

1.this

Inside the function, the value of this depends on to the way the function is called. In strict mode, this will retain the value it had when it entered the execution context, so the following this will default to undefined

function f2(){
  "use strict"; // 这里是严格模式
  return this;
}
f2() === undefined; // true

When a function uses the this keyword in its body, it can be inherited by using function Bind this value to the specific object in the call from the call or apply method of Function.prototype

function add(c, d) {
  return this.a + this.b + c + d;
}
let o = {a: 1, b: 3};
// 第一个参数是作为‘this’使用的对象
// 后续参数作为参数传递给函数调用
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

Calling f.bind(someObject) will create a function with the same function body and scope as f, but In this new function, this will be permanently bound to the first parameter of bind, no matter how this function is called

function f(){
  return this.a;
}
let g = f.bind({a:"azerty"});
console.log(g()); // azerty
let h = g.bind({a:'yoo'}); // bind只生效一次!
console.log(h()); // azerty

In arrow functions, this is consistent with the this of the enclosing lexical context . In the global code, it will be set to the global object

let globalObject = this;
let foo = (() => this);
console.log(foo() === globalObject); // true

2.super

Syntax:
super([arguments]); // Call the constructor of the parent object/parent class Function
super.functionOnParent([arguments]); // Call the method on the parent object/parent class

When used in the constructor, the super keyword will appear alone and must be used with the this key used before the word. The super keyword can also be used to call functions on the parent object

class Human {
  constructor() {}
  static ping() {
    return 'ping';
  }
}

class Computer extends Human {
  constructor() {}
  static pingpong() {
    return super.ping() + ' pong';
  }
}
Computer.pingpong(); // 'ping pong'

3.new

new operator creates an instance of a user-defined object type or an instance of a built-in object with a constructor

function Car() {}
car1 = new Car()
console.log(car1.color)           // undefined
Car.prototype.color = null
console.log(car1.color)           // null
car1.color = "black"
console.log(car1.color)           // black

4. Expansion syntax

You can expand array expressions or strings at the syntax level during function calls/array construction; you can also expand object expressions when constructing literal objects Expand in a key-value manner

Use expansion syntax when calling a function

function myFunction(x, y, z) { }
let args = [0, 1, 2];
myFunction.apply(null, args);

//展开语法
function myFunction(x, y, z) { }
let args = [0, 1, 2];
myFunction(...args);

Use expansion syntax when constructing a literal array

let parts = ['shoulders','knees']; 
let lyrics = ['head',... parts,'and','toes']; 
// ["head", "shoulders", "knees", "and", "toes"]

Array copy

let arr = [1, 2, 3];
let arr2 = [...arr]; // like arr.slice()
arr2.push(4); 

// arr2 此时变成 [1, 2, 3, 4]
// arr 不受影响

Connect multiple arrays

let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
// 将 arr2 中所有元素附加到 arr1 后面并返回
let arr3 = arr1.concat(arr2);

//使用展开语法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
let arr3 = [...arr1, ...arr2];

5. Class expression

Class expression It is a syntax used to define classes

let Foo = class {
  constructor() {}
  bar() {
    return "Hello World!";
  }
};
let instance = new Foo();
instance.bar(); 
// "Hello World!"

6. Function expression

The function keyword can be used to define a function in an expression. You can also use the Function constructor and A function declaration to define a function
Function declaration hoisting and function expression hoisting: Function expressions in JavaScript are not hoisted, unlike function declarations, you cannot use function expressions before defining them

/* 函数声明 */

foo(); // "bar"
function foo() {
  console.log("bar");
}


/* 函数表达式 */

baz(); // TypeError: baz is not a function
let baz = function() {
  console.log("bar2");
};

7.function*Expression

functionThe keyword can define a generator function inside the expression. The function declaration method (function keyword followed by Asterisk) will define a generator function (generator function), which returns a Generator object

Syntax: function* name([param[, param[, ... param]]]) { statements }

function* idMaker(){
  let index = 0;
  while(index<p><strong>Receive parameters</strong></p><pre class="brush:php;toolbar:false">function* idMaker(){
    let index = arguments[0] || 0;
    while(true)
        yield index++;
}

let gen = idMaker(5);
console.log(gen.next().value); // 5
console.log(gen.next().value); // 6

Pass parameters

function *createIterator() {
    let first = yield 1;
    let second = yield first + 2; // 4 + 2 
                                  // first =4 是next(4)将参数赋给上一条的
    yield second + 3;             // 5 + 3
}

let iterator = createIterator();

console.log(iterator.next());    // "{ value: 1, done: false }"
console.log(iterator.next(4));   // "{ value: 6, done: false }"
console.log(iterator.next(5));   // "{ value: 8, done: false }"
console.log(iterator.next());    // "{ value: undefined, done: true }"

Expression

let x = function*(y) {
   yield y * y;
};

Related recommendations:

Introduction to operators == and === in JavaScript_javascript skills

##javascript core language-expression and Operator

The above is the detailed content of Introduction to operators and expressions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.