Variables and Types
JavaScript is dynamically typed, so a variable can hold any value. Declare with const by default, let when you need to reassign.
Like almost every dynamic language, JavaScript is a “duck-typed” language, and therefore every variable is defined using the var keyword, and can contain all types of variables.
We can define several types of variables to use in our code:
let myNumber = 3; // a number
let myString = "Hello, World!" // a string
let myBoolean = true; // a booleanA few notes about variable types in JavaScript:
- In JavaScript, the Number type can be both a floating point number and an integer.
- Boolean variables can only be equal to either
trueorfalse.
There are two more advanced types in JavaScript. An array, and an object. We will get to them in more advanced tutorials.
let myArray = []; // an array
let myObject = {}; // an objectOn top of that, there are two special types called undefined and null.
When a variable is used without first defining a value for it, it is equal to undefined. For example:
let newVariable;
console.log(newVariable); //prints undefinedHowever, the null value is a different type of value, and is used when a variable should be marked as empty. undefined can be used for this purpose, but it should not be used.
let emptyVariable = null;
console.log(emptyVariable);will print out null
Try it
Expected output
myNumber is equal to 4
myString is equal to Variables are great.
myBoolean is equal to falseSolution
let myNumber=4;
let myString="Variables are great.";
let myBoolean=false;
console.log("myNumber is equal to " + myNumber);
console.log("myString is equal to " + myString);
console.log("myBoolean is equal to " + myBoolean);Get the JavaScript agent pack
A battle-tested AGENTS.md, the review checklist, and the failure-mode cheat sheet for JavaScript. One email, then occasional updates when the tooling shifts. No course pitch.
AGENTS.md now — no email needed.