-
Notifications
You must be signed in to change notification settings - Fork 0
The Basics
Time to dive into some syntax!
First, printing. You probably noticed the console.log() function from the previous section. This is how you print stuff to the screen - the same as the print() function in Python. JS also has the console.error() and the console.warn() functions that behave similarly to console.log(), but result in the output looking slightly different.
- Try out the
console.warn()andconsole.error()functions in the browser to see how the output looks different! You'll notice more of a difference in the browser than with Node.js. Feel free to try both runtimes.
// All of these functions print to the console.
console.log('Hello!');
console.warn('你好!');
console.error('¡Hola!');JS uses C-style comments. There are single-line comments (just like # in Python) and multi-line comments (kind of like """ """ in Python).
// This is a single line comment.
/*
This is a
multi-line comment.
*/Unlike Python, there are separate ways to declare a variable and assign to it. Variables must be declared before they are used.
Python:
my_variable = 5
print(my_variable) # Prints 5JavaScript:
let my_variable; // Declare a variable before using it.
my_variable = 5; // Assign a value to the variable.
console.log(my_variable); // Prints 5.
my_variable = 3; // Variables declared with "let" can be assigned new values.Both variables and constants can be declared and assigned to in the same line.
const my_constant = 4;
console.log(my_constant); // Prints 4.
my_constant = 5; // ERROR! You can't reassign a "const" value.Variables are bound by their scope - every place you see a set of {}. Outside of their scope, they are no longer declared. As we'll see shortly, scopes are used in functions, if statements, and loops.
{
let var_in_scope = 4;
console.log(var_in_scope); // This is valid
}
console.log(var_in_scope); // ERROR! var_in_scope stops existing outside of the scope it was declared.If you exclude the declaration (let or const), JS by default will create a global variable with that name. You should avoid this wherever possible.
undeclared_variable = 10; // Won't throw an error, but this can lead to subtle bugs.Optional: you can read about assignment-without-declaration here.
Pre-ES6 JavaScript uses the "var" keyword to declare variables. This will work, but has subtle differences that may cause bugs if you aren't careful.
var old_style_declaration = 10; // Should be avoided. Use 'let' or 'const' instead.Optional: you can read about let vs var here.
Unlike Python, Java, or C, JavaScript makes no distinction between integers and floating point numbers. Instead, every number is technically a float (including array access, which we'll see later!).
There are some exceptions to this with more recent versions of JavaScript. As a beginner, you absolutely do not need to worry about this.
You can do math like usual:
console.log(49 + 51); // 100
console.log(7 / 2); // 3.5
console.log(8 * 8); // 64
console.log(2 ** 3); // 8. This is an exponent operator and will only work on newer browsers.
// Careful! This won't throw an error like in Python.
console.log(1 / 0); // Infinity (if you see this, there's probably a bug in your code).JS also has NaN, which means "Not a Number". This is a special value that is both numeric and not a number. Confusing, right? In practice, it's rarely used. If you see it in your code, there's probably a bug.
// If you interpret this as a multiplication, it doesn't really make sense.
console.log('a' * 4); // NaNnull and undefined are two values in JavaScript that represent the concept of nothing. This is like None in Python. The fact that there are two values to represent nothing is often a source of confusion for beginners, so conceptually they are meant as follows:
-
undefinedmeans a value has been declared but not yet assigned to. -
nullmeans a value has intentionally been assigned an empty or nonexistent reference.
Optional: this picture tries to explain the difference between null and undefined
If that doesn't make sense to you, you're not alone. The good news is that in practice, if a value is either null or undefined, oftentimes we don't care which one it is; we write our code to treat them both the same. This is related to the concept of "falsiness", which we'll see below.
JavaScript has the boolean literals true and false. The basic operators use the same syntax as C or Java:
const mybool = true;
console.log(mybool && false) // Logical AND ("and" in Python), prints false
console.log(mybool || false) // Logical OR ("or" in Python), prints true
console.log(!mybool) // Logical NOT ("not" in Python), prints falseSometimes, you'll see people use an expression that looks like this:
const my_coerced_bool = !!some_varThis funny looking syntax is a way of coercing a value to be boolean. A Python snippet that behaves similarly would be:
my_coerced_bool = bool(some_var)In both examples, the resulting value of my_coerced_bool depends on whether the value of some_var is truthy or falsy.
Several places in JavaScript perform some kind of check to see if a value is true or false (think if-statements and loops). JavaScript allows you to pass any value of any type into these places, so the resulting behaviour is determined by whether the value is truthy or falsy. Falsy values are generally one of false, null, undefined, 0, '' (the empty string). Here's a complete list of falsy values. A truthy value is defined as any value that is not falsy.
A lot of JS code is written that simply checks if a value is truthy or falsy. You'll see some examples in the later section on conditionals. This is why we usually don't care to differentiate whether something is null or undefined, since both are falsy.
Like Python, string literals in JavaScript can be surrounded by single quotes or double quotes.
const my_str = 'this is a valid string';
const my_other_str = "this is also a valid string";JS also has string templates, which allow you to have arbitrary JS expressions inside of them.
const my_template_str = `The answer is ${40 + 2}`;
console.log(my_template_str);
// Prints "The answer is 42". Note the backticks `` and the ${} syntax.Testing if numbers are larger or smaller looks like you'd expect:
console.log(4 > 3); // true
console.log(5 < -4); // false
console.log(4 >= 4); // true
console.log(6 <= 5); // falseA big source of confusion in JavaScript is that there are two operators to test for equality: == and ===. Here's a detailed comparison of the two (optional). As a rule of thumb, the == operator can sometimes produce unexpected results, so you should stick to the === operator.
console.log("SMART" === "SMART"); // true
console.log("SMART" === "smart"); // false
console.log(4 === 4); // true
console.log(false === false); // true