Variables
- Think of a variable as a named box on a shelf where you can store data
- This name allows you to access the contents of the box later
- Variables are crucial in JavaScript and other programming languages because they enable you to store, change, and use data without difficulty
- Historically, in low-level programming languages like assembly, developers had to manage memory directly by specifying precise storage locations, which was complicated and error-prone
- High-level languages like JavaScript simplify this by letting you use simple names for storing and working with data
To create a variable in JavaScript, you use the let
keyword,This keyword declares a variable and creates a named storage space. You then give the variable a name, like firstName
, which is like labeling the box to know where to find your data
- To put a value inside the variable, you use the equal sign (=), which assigns the value to the variable
- For instance, let
firstName = John;
assigns the text “John” to the variable named firstName
Variable Types / Data Types
Variables in JavaScript can hold different types of data, known as variable types or data types
- Strings: Used for text data, . String values are always enclosed in double quotation marks
- Numbers: Used for numerical values, Number values do not need to be enclosed in quotation marks. This helps JavaScript differentiate between text and numbers
- Boolean: Represents a simple true or false value, Booleans are like yes/no answers used for making decisions and tracking conditions, . They do not require any extra symbols like quotes
- For example,
true
is a boolean value:isTaskComplete = true;
- For example,
Operators
JavaScript also uses operators to perform actions, . Arithmetic operators are tools used to perform operations with numbers. . They are symbols or commands that tell JavaScript to do something, similar to mathematical operators. The basic arithmetic operators covered are:
- Addition (+): Used to add numbers
- Subtraction (-): Used to subtract one number from another, For example,
numberOne
-numberTwo
- Multiplication (*): Used to multiply numbers
- Division (/): Used to divide one number by another
NOTE
You can store the result of an operation in a new variable For example,
let sum = numberOne + numberTwo;
would calculate the sum and store it in the sum variable
To see what is happening in your code or display messages, you can use console.log()
Placing a variable inside the parentheses of console.log() will print its value to the console
You can also use console.log() to print multiple items, often including a descriptive label as a string followed by the value, by separating them with a comma inside the parentheses