Variables
Valid Variable Name 合法的变量名
- employee_77
- Variable_name
- x
- Name_code
- name_code
- _emp_name
Invalid Variable Name 非法的变量名
- var // var is reserve word.
- 77employee // Initial character is a number.
- Variable%name // % character is not allowed.
- Name&code // & is not allowed.
Declaring Variables
With the keyword var, followed by name of the variable.
var emp_name
The above syntax can be used to declare both local and global variables.
Another way to declare a variable is simply assigning it a value.
x=12.2 emp_code = 'E123'
// Declaring a variable // Best Practices var emp_code = 'E123'; // Poor Practices emp_code = 'E123' // Declaring multiple variables. Use one var statement and declare each variable on a new line. // Best Practices var emp_list = emplist(), x = 12, str1 = 'String1'; // Poor Practices var emp_code = emplist(); var x = 12 ; var str1 = 'String1'; // Declare unassigned variables last. // Best Practices var roll_no = 12, name, class; // Poor Practices var name class, roll_no = 12;
Evaluating Variables
A variable or array element that has not been assigned a value, has the value undefined.
The result of evaluating an unassigned variable depends on how it was declared:
If the unassigned variable was declared with var, the evaluation results in the undefined value or NaN in numeric contexts.
If the unassigned variable is declared without var statement, the evaluation results in a run time error.
一个变量或者数组元素没有被分配初始值,其值为undefined
未赋值变量的值取决于这个变量是怎么声明的
如果未赋值变量是通过var进行声明的,则它的值为undefined或者NaN
如果未赋值变量没有使用var进行定义,在执行表达式的过程中将发生运行时异常
See the following statements :
var x; print("The value of x is : " + x); // prints "The value of x is : undefined" print("The value of y is : " + y); // throws reference error exception
You can use undefined to determine whether a variable has a value.
In the following statements, the variable x is not assigned a value, and the if statement evaluates to true.
var x; if(x === undefined) { do something ; } else { do something ; }
Variables Scope
The variables can be declared and used in two ways locally and globally.
When you declare a JavaScript variable within a function, it is called a local variable because the variable is available only within the function.You can use same variable name within different function.
When you declare a variable outside a function it is called global variable.You can optionally declare a global variable using var (for example var empCode).
However, you must use var to declare a variable inside a function.
变量的定义和使用分两种:局部变量和全局变量
如果在函数中定义变量,则该变量是局部变量,它只在函数体类有效
不同的函数中,可以定义相同名称的变量,互不影响
在函数体外可以随意的通过var关键字定义的变量,称为全局变量
尽管如此,在函数内部声明变量时,必须使用var进行声明
(注意:函数的参数除外,而且函数的参数不能用var声明)
Check whether a variable is defined or not in JavaScript
To check whether a variable is defined or not, you can use the typeof operator.
The following alert will return "undefined" i.e. the variable "abc" is not defined.
if (typeof abc === 'undefined') { // variable abc is undefined }
检查一个变量是否已经定义,通过typeof进行判断
如果未定义,则typeof(x)==="undefined"
如果未定义,直接alert(x),将抛异常
如果已经定义,但未分配值,则x===undefined
如果已经定义,且已分配至,则类型为值所对应的类型
var x; alert(x===undefined);//true alert(typeof(x)==="undefined");//true var a = 1; alert(typeof(a)==="number");//true showType(typeof(a)); var b = ""; alert(typeof(b)==="string");//true showType(typeof(b)); var c = []; alert(typeof(c)==="object");//true showType(typeof(c)); var d = {}; alert(typeof(d)==="object");//true showType(typeof(d)); var e = function() {alert("i am a fn");}; alert(typeof(e)==="function");//true showType(typeof(e)); function showType(type) { switch(type) { case "number": alert("type is number"); break; case "string": alert("type is string"); break; case "function": alert("type is function"); break; case "object": alert("type is object"); break; default: alert("wrong type!"); break; } }
Constants
In JavaScript, constants are declared with const keyword and assigned at the time of the declaration. A constant can be global or local to a function where it is declared
Constants are read-only, therefore you can not modify them later on.
Naming a constant in JavaScript follow the same rule of naming a variable except that the const keyword is always required, even for global constants.
If the keyword is omitted, the identifier is assumed to represent a variable.
JavaScript中,常量在声明时便初始化赋值。
常量可以是全局的或者局部的。
常量是只读的,一旦声明,后面都不能再改变。
常量定义使用的关键字const 必须写,如果省略,将被认为是普通变量定义。
在同一个作用范围内,不要定义同名的常量或者变量。下面的语法将导致错误。
const country = 'India'; //You cannot declare a constant with the same name as a function // or variable in the same scope. Following statements create error. function abc() { const abc = 55; } function abc() { const x = 15; var x; }
同一个范围内,如果出现同名的变量或者函数,后者会覆盖前者;
但是,对于常量,后者无法覆盖前者,只要前者是以常量方式定义的,其值就不会再变。
var country = "EN"; const country = "US"; alert(country);// US
const country = "EN"; const country = "US"; alert(country); //EN
Data Type
JavaScript recognizes the following types of values
String: "google.com", 'yahoo.com'
Numbers:45, 45887, -45, 12.23, -145.55
Logical (Boolean):true, false
null:empty value or nothing. Since JavaScript is case-sensitive, null is not the same as Null, NULL
undefined:whose value is undefined
Data Type Conversion
JavaScript is a dynamically typed language.
Therefore there is no need to specify the data type of a variable at the time of declaring it.
Data types are converted automatically as needed during script execution.
JavaScript 是一门动态语言
因此在变量声明时,不需要指定其具体类型
数据类型在脚本执行的时候将自动转换
var age = 21; age = "What is your age?";
x = "What is your age ?" + 21 // returns "What is your age ?21 " y = 21 + " is my age. " // returns "21 is my age." "21" - 7 // returns 14 "21" + 7 // returns "217" "21" + "7" // returns "217" "21" * 7 // returns 147 "21" / 7 // returns 3
Array literals
In Javascript an array literal is a list of expressions, each of which represents an array element, enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified. If no value is supplied it creates an empty array with zero length.
//Creating an empty array : var fruits = [ ]; //Creating an array with four elements. var fruits = ["Orange", "Apple", "Banana", "Mango"]; //Creating an empty array that has 5 elements. var fruits = [5];
使用new关键字来创建数组
var fruits = new Array("Orange", "Apple", "Banana", "Chery");
Comma in array literals
There is no need to specify all elements in an array literal. If we put two commas in a row at any position in an array then an unspecified element will be created in that place.
The following example creates the fruits array :
fruits = ["Orange", , "Mango"]This array has one empty element in the middle and two elements with values. ( fruits[0] is "Orange", fruits[1] is set to undefined, and fruits[2] is "Mango").
If you include a single comma at the end of the elements, the comma is ignored. In the following example, the length of the array is two. There is no fruits[2].
fruits = ["Orange", "Mango",]
In the following example, the length of the array is four, and fruits[0] and fruits[2] are undefined.
fruits = [ , 'Apple', , 'Orange'];
Integer literals
1. Decimal ( base 10)
Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no leading zeros.
Example : 123, -20, 12345
2. Hexadecimal ( base 16)
Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, E, F or a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal.
Example : 7b, -14, 3039
3. Octal (base 8)
Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number is octal.
Example : 173, -24, 30071
Floating number literals
A floating number has the following parts.
- A decimal integer. 整数位
- A decimal point ('.'). 小数点
- A fraction. 小数位
- An exponent. 幂
The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-").
- 8.2935
- -14.72
- 12.4e3 [ Equivalent to 12.4 x 103 ]
- 4E-3 [ Equivalent to 4 x 10-3 => .004 ]
Boolean literals
The Boolean type has two literal values :
- true
- false
Object literals
An object literal is zero or more pairs of comma separated list of property names and associated values, enclosed by a pair of curly braces.
In JavaScript an object literal is declared as follows:
1. An object literal without properties:
var userObject = {}
2. An object literal with a few properties :
var student = {
First-name : "Suresy",
Last-name : "Rayy",
Roll-No : 12
};
Object literals maintain the following syntax rules:
- There is a colon (:) between property name and value. 属性名与值用冒号分割
- A comma separates each property name/value from the next.不同键值对用逗号分割
- There will be no comma after the last property name/value pair.最后一个键值对不跟逗号
String literals
JavaScript has its own way to deal with string literals. A string literal is zero or more characters, either enclosed in single quotation (') marks or double quotation (") marks.
You can also use + operator to join strings. The following are the examples of string literals :
- string1 = "w3resource.com"
- string1 = 'w3resource.com'
- string1 = "1000"
- string1 = "google" + ".com"
In addition to ordinary characters, you can include special characters in strings, as shown in the following table.
string1 = "First line. \n Second line."