Table of Contents
How to declare variables
function a way to declare variables?
var, let and const:
Variable declaration promotion
Duplicate declaration
The scope of the scope
const 的特殊之处
Home Web Front-end JS Tutorial What are the 4 ways to declare variables in javascript

What are the 4 ways to declare variables in javascript

Apr 01, 2021 pm 05:40 PM
javascript declare variables

Four ways to declare variables in JavaScript: 1. Use "var" to declare variables, such as "var a;"; 2. Use "function" to declare variables, such as "function Fun (num) {}"; 3. Use "let" to declare variables; 4. Use "const" to declare variables.

What are the 4 ways to declare variables in javascript

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

How to declare variables

There are several ways to declare variables in JavaScript:

  • Before ES6, it was var and function
  • New in ES6 Is adding let and const

function a way to declare variables?

Let’s verify it

Verification method one:

    function repeatFun (num) {
      return num;
    }

    repeatFun(10); // 10

    var repeatFun = 1;

    repeatFun(2); // Uncaught TypeError: repeatFun is not a function
Copy after login

This method uses var to repeatedly declare variables, but the latter will overwrite the former feature

Let’s take a look at what happened here:

  • First, a function is declared, his name is repeatFun
  • , and then called once, the result is 10
  • After that, repeatFun is declared again with var, and initialized to 1
  • The function repeatFun is called one last time
  • The result is an error, content: repeatFun is not a function

According to the execution results, we can infer that there is a repeatFun variable in the browser's memory. It was a function before and was later redeclared by a var keyword and initially changed to 1.

Verification method two:

    {
      let repeatFun = 1;
      function repeatFun (num) {
        return num
      }
    }
    // Uncaught SyntaxError: Identifier 'repeatFun' has already been declared
Copy after login

The second method is to use a syntax of

ES6: using the feature of let that cannot be declared repeatedly to prove that function is also a declared variable The difference between


var, let and const:

  • Variable declaration promotion

    • var has variable declaration promotion Functions can be used first and then declared, and vice versa.
    • let and const do not have the function of variable declaration promotion. They must be declared first before they can be used.
  • Repeated declaration

    • var can be declared repeatedly, and the latter covers the former
    • let and const cannot be repeatedly declared
  • scope The scope of

    • var's scope is bounded by functions
    • let and const are block scope
    • var can define global variables and local variables, let and const can only define local variables
  • The special thing about const

    • cannot be modified after declaration (there are some differences in the behavior of reference types and basic types) Different)

Variable declaration promotion

  • var has the function of variable declaration promotion, which can be used first and then declared
  • let and const do not have the function of variable declaration promotion. They must be declared first before they can be used.

Example 1, verify var variable promotion:

var b = a + 1; // b: NaN 
var a = 1; // a: 1
Copy after login

First, declare it A variable b is initially recognized, and the initialized value is a 1 (what is the value of a?) <br/> Then a variable a is declared, and the initial recognition is 1 <br/> This is what the code looks like on the surface When doing these things, what is actually done is this:

  • Every time a variable is declared, their declaration is placed at the top of the code, and they are all performed once Initialization, the value is: undefined, but the assignment position will not change,
  • Then perform other operations

The following writing method can also achieve the same effect

var b;
var a;

b = a +1; // b: NaN 
a = 1; // a: 1
Copy after login

let and const behave differently from var

Example 2, verify whether there is variable promotion in let:

let b = a + 1; // Uncaught ReferenceError: a is not defined
let a = 1;
Copy after login

A scope error will be thrown directly when running. If you change it like this, There is no error:

let a = 1; // a: 1
let b = a + 1; // b: 2
Copy after login

const and let perform the same in terms of variable promotion


Duplicate declaration

  • var can be declared repeatedly, and the latter overrides The former
  • let and const cannot be declared repeatedly

    Example 1, verify the repeated declaration of var:

    var a = 1;
    var a = 2;
    var b = a + 1; // 3
    Copy after login
    • First, declare the variable a, initialized as 1
    • Then declare variable a again, initialized to 2
    • Finally declare variable b, its initial value is a 1

    Example 2, verify the repetition of let Statement:

    let a = 1;
    let a = 2; // Uncaught SyntaxError: Identifier &#39;a&#39; has already been declared
    Copy after login
    var a = 1;
    let a = 2; //Uncaught SyntaxError: Identifier &#39;a&#39; has already been declared
    Copy after login
    • Obviously, variables declared using let in the same execution environment cannot be declared repeatedly, otherwise an error will be thrown <br/> const and let behave the same in terms of repeated declarations

The scope of the scope

  • The scope of var is bounded by the function
  • let and const are Block scope
  • var can define global variables and local variables, let and const can only define local variables

encapsulates a factorial function as an example, without using tail recursion, just use for Implementation with if <br/> Example 1, factorial function verifies the scope:

  var num = 5;

  function factorial(num) {

      var result = 1,resultValue = 0;

      for (let i = num - 1; i >= 1; i--) {

        if (i === num - 1) {
          resultValue = num * i;
        }else{
          resultValue = num * i / num;
        }

        result *= resultValue;
      }

      // i 是用 let 进行定义它的作用域仅仅被限制在 for 循环的区域内
      // i++;// Uncaught ReferenceError: i is not defined

      return result;
  }

  // result 是用 var 进行定义,他的活动区域在 factorial 函数内
  // result++; // var的作用域.html:34 Uncaught ReferenceError: result is not defined

  factorial(num); // 120
Copy after login

const behaves the same as let in the scope

Example 2, verifies const Scope:

  {
    const NUM_1 = 10;
  }

  let b = NUM_1 + 1;  // Uncaught ReferenceError: NUM_1 is not defined
Copy after login

Example 3, verify that var can define global variables, let and const can only define local variables

  // 可以挂载到全局作用域上
  // var name = &#39;window scoped&#39;;

  let name = &#39;let scoped&#39;; //是不挂载到全局作用域中

  let obj = {
    name: &#39;myName&#39;,
    sayName () {

       return function () {
        console.log(this.name); // 打印出来为空
      };
    }
  }

  obj.sayName()();
  console.log(window); //name 这个属性的值没有,如下图
Copy after login

What are the 4 ways to declare variables in javascript

若这样改一下就可以得到我们想要的值:

  • 把用 var 定义的 name 的代码取消注释,把用 let 定义的 name 的代码注释。

这个同时也涉及到新问题 this 的指向。后面的文章再详细举例验证


const 的特殊之处

const 与 let , var 其实还是有些地方不一样的

例子1:验证 const 的特殊之处(一)<br/>

const NUM = 100; 
 NUM = 1000; // Uncaught TypeError: Assignment to constant variable
Copy after login
  • 经过 const 方式进行声明,之后赋值完毕,则不可以进行改变,否则会报错

但是也有例外

例子二:验证 const 的特殊之处(二)

  const obj = {
    name: &#39;xiaoMing&#39;,
    sayName () {
      return this.name
    }
  };
  obj.sayName(); // xiaoMing

  obj.name = &#39;xiaoHong&#39;;
  obj.sayName(); // xiaoHong
Copy after login
  • 使用 const 首先声明一个变量 obj , 并且这个变量指向我们在内存中创建的对象,你会发现我们改变里面的属性是没有任何问题

若这样改一下: <br/> 例子三:验证 const 的特殊之处(三)

  const obj = {
    name:&#39;xiaoMing&#39;,
    sayName(){
      return this.name
    }
  };

  obj = {}; // Uncaught TypeError: Assignment to constant variable
Copy after login
  • 若改变该变量的指向的对象,则就会报错。这种错误和 「 验证 const 的特殊之处(一)」的错误是一样的

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of What are the 4 ways to declare variables in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles