JavaScript Variables
In a programming language and in algebra named variables are used to store data values.
JavaScript uses the var keyword to define variables.
JavaScript uses arithmetic operators to compute values just like algebra:
An equal sign is used to assign values to variables just like algebra.In this example, length is defined as a variable. Then, it is given the value 6:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var length; length = 6; document.getElementById("demo").innerHTML = length; </script> </body> </html>
A literal is aconstant value. A variable is a name. A variable can be assigned variable values.JavaScript Operators
JavaScript uses arithmetic operators to compute values just like algebra:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = (5 + 6) * 10; </script> </body> </html>
JavaScript uses an assignment operator to assign values to variables like algebra:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var x, y, z; x = 5 y = 6; z = (x + y) * 10; document.getElementById("demo").innerHTML = z; </script> </body> </html>JavaScript Statements In HTML
JavaScript statements are written as sequences of "executable commands" Statements are separated by semicolons:
x =5+6; y = x *10;JavaScript Keywords
A JavaScript statement often starts with akeyword. The var keyword tells the browser to create a new variable:
JavaScript Identifiersvarx =5+6; vary = x *10;
All programming languages must identify variables with unique names. These unique names are called identifiers. Identifiers can contain letters, digits, underscores, and dollar signs, but cannot begin with a number. Reserved words like JavaScript keywords cannot be used as identifiers.
JavaScript Comments
Not all JavaScript statements are "executable commands". Anything after double slashes // is treated as comments, ignored, and not executed:
Will not be executed In this tutorial, we use colors to highlight reserved words, values, and comments.// x = 5 + 6;
JavaScript Data Types
JavaScript variables can hold many data types: numbers, text strings, arrays, objects and much more:
The Concept of Data Typesvarlength =16; // Number assigned by a number literal varpoints = x *10; // Number assigned by an expression literal varlastName ="Johnelwin"; // String assigned by a string literal varcars = ["Saab","Volvo","BMW"]; // Array assigned by an array literal varperson = {firstName:"John", lastName:"Elwin"}; // Object assigned by an object literal
In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type. Without data types, a computer can not safely solve this:
Does it make any sense to add "Volvo" to sixteen?16+"Volvo"
Will it produce an error or a result?
"16Volvo"You will learn much more about data types in a later chapter.