- JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and much more.
- The core client-side JavaScript language consists of some common programming features that allow you to do things like:
- Store useful values inside variables.
- Operations on pieces of text (known as “strings” in programming).
- Running code in response to certain events occurring on a web page.
- Variables are containers for storing data (storing data values).
- There are 4 ways to declare a JS Variable:
- Using var
- Using let
- Using const
- Using nothing
- The var keyword is used in all JavaScript code from 1995 to 2015.
- The let and const keywords were added to JavaScript in 2015.
- If you want your code to run in older browser, you must use var.
- If you want a general rule: always declare variables with const.
- If you think the value of the variable can change, use let.
- Just like in algebra, variables hold values
- Just like in algebra, variables are used in expressions
-
Variables are containers for storing values.
- All JavaScript variables must be identified with unique names. These unique names are called identifiers.
- Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
- The general rules for constructing names for variables (unique identifiers) are:
- Names can contain letters, digits, underscores, and dollar signs.
- Names must begin with a letter
- Names can also begin with $ and _ (but we will not use it in this tutorial)
- Names are case sensitive (y and Y are different variables)
- Reserved words (like JavaScript keywords) cannot be used as names
- In JavaScript, the equal sign (=) is an “assignment” operator, not an “equal to” operator.
-
The “equal to” operator is written like == in JavaScript.
- JavaScript variables can hold numbers like 100 and text values like “John Doe”.
- In programming, text values are called text strings.
-
Strings are written inside double or single quotes. Numbers are written without quotes. If you put a number in quotes, it will be treated as a text string.
- Creating a variable in JavaScript is called “declaring” a variable.
- You declare a JavaScript variable with the var or the let keyword
- After the declaration, the variable has no value (technically it is undefined).
- To assign a value to the variable, use the equal sign
- You can also assign a value to the variable when you declare it
- It’s a good programming practice to declare all variables at the beginning of a script.
- You can declare many variables in one statement. Start the statement with let and separate the variables by comma.
Value = undefined:
- In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.
- A variable declared without a value will have the value undefined
Re-declaring JS Variables