Variables and data types — JavaScript
What is this and why?
Imagine that your computer is a huge desk. On it lie textbooks, notebooks, pens, and, of course, your smartphone. To quickly find the right thing, you put each item in its place. In programming, it's the same: when a program runs, it needs somewhere to store numbers, words, and other data. For this, there are variables.
A variable is like a box with a label. On the label, you write a name (for example, "myAge"), and inside you put a value (for example, 12). When you need that value, you just say: "Give me what's in the box named myAge".
A data type is a rule about what exactly can be put in the box. In one box, you can only put numbers, in another — only text, in a third — only true or false statements (yes/no). If you try to put text in a box meant for numbers, the computer will get confused. Therefore, it's important to know what types exist and how to use them correctly.
In JavaScript (JS), data types work almost like in Python, but there are important differences. For example, in Python you write age = 12, and Python itself guesses that 12 is a number. In JavaScript, it's the same, but there are nuances: JS is sometimes too "guessing" and might do something you don't expect. So we will learn to explicitly state what we want.
Why is this needed? Imagine you are writing a calculator program. If you mix up types and add the number 5 to the text "5", you will get not 10, but "55" (five fives in a row). The computer will do as you said, not as you thought. Therefore, knowledge of data types is a superpower that helps avoid stupid mistakes.
Code examples with explanation
Let's get straight to practice. Open any code editor (for example, the one built into the browser by pressing F12 and going to the Console tab) or use an online editor like CodePen or JSFiddle. Write the code and see what happens.
Example 1: Creating variables with numbers
// Create a variable named "myAge" and put the number 12 in it
let myAge = 12;
// Create a variable "pi" and put the fractional number 3.14 in it
let pi = 3.14;
// Create a variable "negativeNumber" and put the negative number -5 in it
let negativeNumber = -5;
// Output the values to the screen
console.log("My age:", myAge); // Will output: My age: 12
console.log("Pi number:", pi); // Will output: Pi number: 3.14
console.log("Negative number:", negativeNumber); // Will output: Negative number: -5
// Now let's try to add two numbers
let sum = myAge + pi; // 12 + 3.14 = 15.14
console.log("Sum of age and Pi:", sum); // Will output: Sum of age and Pi: 15.14
// Note: in JavaScript, the fractional part is separated by a dot, not a comma!
// If you write 3,14 — it will be an error, because the comma has a different meaning.
Explanation: We used the keyword let. It tells JavaScript: "Create a new box". After that, we wrote the variable name (myAge), an equals sign (=), and the value (12). The equals sign here does not mean "equals" in the mathematical sense. It means "put in the box". In Python, you would write the same thing: my_age = 12. The difference is only that in JavaScript it's common to use camelCase (first word lowercase, each subsequent word capitalized), and in Python — snake_case (words separated by underscores).
Example 2: Text strings (String)
// A string is any text. It needs to be enclosed in quotes.
let myName = "Anna"; // Double quotes
let myCity = 'Moscow'; // Single quotes — also works!
let myHobby = `drawing`; // Backticks — a modern way
// Output the strings
console.log("My name is:", myName); // Will output: My name is: Anna
console.log("I live in the city:", myCity); // Will output: I live in the city: Moscow
console.log("My hobby is:", myHobby); // Will output: My hobby is: drawing
// Strings can be concatenated (concatenation)
let greeting = "Hello, " + myName + "! You live in " + myCity + ".";
console.log(greeting); // Will output: Hello, Anna! You live in Moscow.
// You can also insert variables directly into a string using backticks
let greetingModern = `Hello, ${myName}! You live in ${myCity}.`;
console.log(greetingModern); // Will output the same: Hello, Anna! You live in Moscow.
// Note: ${...} is a special syntax that only works with backticks.
// This is very convenient, you don't need to constantly put plus signs!
Explanation: In Python, strings can also be created with single or double quotes. But in JavaScript, there is an additional type — backticks (`` ` ``). They allow you to insert variables directly into the text using ${}. This is called template strings. In Python, f-strings are used for this: f"Hello, {my_name}!". The principle is the same, just the syntax is different.
Example 3: Boolean type — true or false
// The Boolean type can only have two values: true or false
let isStudent = true; // I am a student — this is true
let hasPets = false; // I don't have pets — this is false
console.log("Am I a student?", isStudent); // Will output: Am I a student? true
console.log("Do I have pets?", hasPets); // Will output: Do I have pets? false
// Boolean values are often obtained as a result of comparisons
let myAge = 12;
let drivingAge = 18;
let canDrive = myAge >= drivingAge; // 12 >= 18? This is false!
console.log("Can I drive a car?", canDrive); // Will output: Can I drive a car? false
// More comparison examples:
let number1 = 10;
let number2 = 20;
console.log("Is 10 greater than 20?", number1 > number2); // Will output: Is 10 greater than 20? false
console.log("Is 10 less than 20?", number1 < number2); // Will output: Is 10 less than 20? true
console.log("Is 10 equal to 20?", number1 === number2); // Will output: Is 10 equal to 20? false
// Note: in JavaScript, triple equals === is used for comparison.
// Double equals == also works, but it can give unexpected results.
// For example: 5 == "5" will give true (JavaScript converts the string to a number),
// but 5 === "5" will give false (because the types are different).
// So it's better to always use === to avoid surprises.
Explanation: In Python, the Boolean type is written as True and False (capital letters). In JavaScript, they are written in lowercase: true and false. Also, in Python, comparison is done with == (double equals), and there is no ===. In JavaScript, it's recommended to use === to avoid automatic type conversion, which can lead to errors.
Example 4: Special value — undefined
// undefined means "value not assigned"
let myFutureJob;
console.log("My future job:", myFutureJob); // Will output: My future job: undefined
// This happens if you created a variable but didn't put anything in it.
// The box exists, but it's empty.
// Another way to get undefined is to try to access a non-existent property
let emptyObject = {};
console.log("Non-existent property:", emptyObject.something); // Will output: Non-existent property: undefined
// undefined is different from null. null means "empty value intentionally"
let emptyValue = null;
console.log("Empty value:", emptyValue); // Will output: Empty value: null
// null is often used when you want to say "there is no value here yet, but it will appear later"
// For example, in a game: let currentEnemy = null; // no enemy on the screen yet
Explanation: In Python, there is None instead of null and undefined. In JavaScript, there are two separate values: undefined (the variable exists but has no value) and null (the value is intentionally empty). In Python, None is used for both cases. This is an important difference: in JavaScript, you need to distinguish between "not assigned" and "intentionally empty".
How to check the type of a variable?
In JavaScript, there is a special operator typeof that helps you find out what type is stored in a variable. This is very useful when you are not sure what the program gave you.
let myAge = 12;
let myName = "Anna";
let isStudent = true;
let emptyValue = null;
let notDefined;
console.log(typeof myAge); // Will output: "number"
console.log(typeof myName); // Will output: "string"
console.log(typeof isStudent); // Will output: "boolean"
console.log(typeof emptyValue); // Will output: "object" — this is a known JavaScript bug!
console.log(typeof notDefined); // Will output: "undefined"
// typeof returns a string with the type name. This can be used in conditions:
if (typeof myAge === "number") {
console.log("myAge is a number, you can do math with it!");
}
// But be careful with null: typeof null returns "object", although null is not an object.
// This is a historical mistake in JavaScript that cannot be fixed because
// too many programs already rely on this behavior.
Explanation: In Python, the type() function is used for this: type(my_age) will return <class 'int'>. In JavaScript, typeof returns a simple string like "number". This is convenient for quick checks. But remember the bug with null: typeof null returns "object", although this is incorrect. This is a classic JavaScript joke that all developers know about.
What's the result?
Now you know the basic data types in JavaScript:
- Number — numbers (integers and fractions)
- String — text strings
- Boolean — true/false
- undefined — value not assigned
- null — intentionally empty value
These are the building blocks from which any program is built. In the next article, we will learn how to work with more complex structures: arrays (lists) and objects (dictionaries). But first, practice with simple types: create different variables, try to add a number to a string, see what happens. Experiment! This is the best way to understand how JavaScript works.
Homework:
- Create a variable with your name and a variable with your age.
- Create a greeting string using template strings (backticks).
- Check what type the result of the expression
"10" - 5gives. Why did this happen? - Try to add
nullto a number. What happens? Why?
Write your answers in the comments or check them in the console. Good luck!