When declaring variables in Javascript, although using the var keyword and not using the keyword often runs without problems, there are still differences between the two ways. Code that runs normally does not mean it is appropriate code.

var num = 1;

It declares a variable in the current scope. If declared in a method, it is a local variable; if declared in the global scope, it is a global variable.

and

num = 1;

In fact, it is an assignment operation to a property. First, it will try to resolve num in the current scope chain (if declared in a method, the current scope chain represents the global scope and the method's local scope, etc...). If num is found in any current scope chain, it will perform the assignment to the num property. If num is not found, it will create a num property in the global object (i.e., the top-level object of the current scope chain, such as the window object) and assign a value to it.

Note! It does not declare a global variable, but creates a property of the global object.

Even so, you may still find it hard to understand the difference between "variable declaration" and "creating an object property" here. In fact, Javascript variable declarations, property creation, and every property in Javascript have certain flags that describe their attributes, such as ReadOnly, DontEnum, DontDelete, etc.

Because variable declarations come with a non-deletable attribute, compare var num = 1 and num = 1. The former is a variable declaration, which has a non-deletable attribute, so it cannot be deleted; the latter is a property of the global object, so it can be deleted from the global object.

// num1为全局变量,num2为window的一个属性
var num1 = 1;
num2 = 2;
// delete num1;  无法删除
// delete num2;  删除
function model(){
var num1 = 1; // 本地变量
num2 = 2;     // window的属性
    // 匿名函数
    (function(){
        var num = 1; // 本地变量
        num1 = 2; // 继承作用域(闭包)
        num3 = 3; // window的属性
    }())
}

PS: In the ECMAScript5 standard, there is a "Strict Mode". In strict mode, assigning a value to an undeclared identifier will throw a reference error, thus preventing the accidental creation of global object properties. Currently, new versions of some browsers already support it.