Fundamentals
To import a Javascrpt (JS) file into an HTML file, you use the following in the <head> section:
<script src="(the file name).js"></script>
The Var, the Let, and the Const variables
There are three main types of variables: var, let, and const.
var is an outdated means of assigning variables. The value assigned to it can be changed later. let is the more modern version of var. Like var, the value it is assigned to can be changed later. const is the final primary variable. const variables CANNOT be changed after assignment. They should be used over var or let, UNLESS you plan for their assigned variable to be changed.
Using variables for calculating + The DRY Principle
There are some basic operators you can use in JavaScript.
// Instead of typing the two age const variables like this... const now = 2037; const ageJones = 2037 - 1991; const ageSarah = 2037 - 2000; // You can do this instead! const now = 2037; const ageJones = now - 1991; const ageSarah = now - 2000;
You can easily use variables to calculate things for other variables, if-statements, etc, as long as the datatypes of the saved variable’s contents is able to be used in those calculations. It’s also preferable that you do this whenever you can, because of the DRY principle that most coding languages use.
The DRY principle is an acronym for “Don’t Repeat Yourself”, and it is exactly what it’s name suggests: If you can avoid repeating typing the same code in multiple places, then you should avoid it and find some way to compact your code for re-usability like the above example. There’s two reasons for this: A) It makes your code easier to read and understand, and B) If you have to change something in one place, you don’t have to change it everywhere else you used the code in.
Basic Math Operators
// Basic math operators console.log(2 * 3, 4 / 2, 2 ** 3);
Above is a console.log() that has some basic math operators, those being the multiplication operator (2 * 3), the division operator (4 / 2), and the power-of operator (2 ** 3). The multiplication operator is identified through the singular * between two numbers; likewise the division operator is the same, only with / instead of *. The final basic math operator is the power-of operator, which is identified by ** (two * put together)
To combine different strings together, the most basic way of doing so is by concatenating them.
// Concatenating strings const firstWord = 'Concatenating'; const secondWord = 'Strings'; console.log(firstWord + ' ' + secondWord);
It’s not exactly pretty to look at, nor is it easy to type, but it works for the time being until one learns about template literals, which will help massively.
Coercion
While still on this topic, it’ll be a good thing to note that JavaScript has something called type coercion, or the automatic changing of one datatype to another (such as a number to a string).
// Type coercion example const number5 = 5; const string9 = '9'; let sum = number5 + string9; // The console will log "59" console.log(sum);
Type coercion will automatically convert one datatype into another when the situation requires it; in this case, it converted the number5 variable into a string in order to concatenate it and the string9 variable together to form “59”. The compiler could’ve chose to make them both numbers before returning a sum of 14, but it did not. To return this result, you have to implicitly (manually) convert the '9' into a number using the Number() method.
// Now this will give the expected number 14. sum = number5 + Number(string9);
Assignment Operators
// Will allow you to assign the operation result to x. In this case, it's 15 let x = 10 + 5 //// Some handy shorthands for math operands + variable assigning // Shorthand for "x = x + y" x += y // Shorthand for "x = x - y" x -= y // Shorthand for "x = x * y" x *= y // Shorthand for "x = x / y" x /= y //// Increment shorthands // Increases a counter by 1 x++; // Decreases a counter by 1 x--;
(Note for x++ / x--, they won’t really come up until we learn about loops later.)
Comparison Operators
//// >, <, ==, ===, >=, <= // Note: '==' and '===' will be discussed down below, and will be skipped here // '>' is the greater-than symbol, it checks if item 1 is greater than item 2 // '<' is the less-than symbol, it checks if item 1 is smaller than item 2 // '>=' is the greater-than-or-equal symbol, it checks if item 1 is greater than OR equal to item 2 // '<=' is the less-than-or-equal symbol, it checks if item 1 is less than OR equal to item 2
Datatypes
There are multiple types in JavaScript (and any coding language for that matter). You can use “typeof” + “(a value)” to see these types. As another thing, JavaScript has dynamic typing, users DO NOT have to manually assign the data type to a variable.
Boolean values are either true or false and nothing else. Used for taking decisions. Putting '!' in front of a boolean will invert the boolean result.
String is anything between single or double-quotes. They represent physical text such as letters, spaces, symbols, etc.
Number represent floating-point (decimals) and integers (rounded numbers).
Undefined represents values that haven't been defined yet. (Such as var age;)
Null also means empty value, much like undefined
Symbol means characters that represents exclusively symbols. ("%", "#", "*", etc.)
BigInt is like Number, but used for larger lengths of integers that Number can't hold.
Concatenating Strings
When using strings, you either have to do two things to import outside data into the string. Either you have to concatenation the string, I.E:
// A basic concatenation
const numm = 25;
console.log("Hello" + numm + "World!");
OR you could use template literals. Template literals allows you to just import the data (mostly variables) into the string directly without having to do the complicated string splitting above. To do a template literal, you have to swap out the quotation marks in the string with the grave accent (the symbol above the TAB key), and the data you want to get inserted is wrapped in “${}” (a dollar sign + open and close curly brackets)
// A basic template literal
const numm = 25;
console.log(`Hello ${numm} World!`);
The If & If-Else Statements
To take decisions in JavaScript, one of the best bets is to use an if-else statement. If-else statements are simple: They check to see if a value is true or not, and if they are, they execute the code inside their code block and exit right afterwards. If not, then they check any other conditions in any “else” statements following the initial if-statement.
// A basic if-else statement
const javescriptFun = true;
if (javascriptFun) {
console.log('JavaScript is fun! :D');
} else {
console.log('Why would you say JavaScript is not fun? :(');
}
Comparing datatypes with ‘==’ and ‘===’
When comparing data types, you could use ‘==’ or ‘===’ to return a boolean value. ‘==’ means “roughly equal” or “lazy type checking”, which only compares the actual values of what’s being compared and not their datatypes.
// An example of '==', which does a lazy comparison check. With '==', the console will log true because the actual values are the same
console.log('123' == 123);
On the other hand, ‘===’ is often referred to as “strict type checking”; using this comparison WILL check the datatype of what’s being compared, in addition to checking their values.
// An example of '===', which will yield false because their datatypes don't match
console.log('123' === 123);
Its often better to use the strict checking to prevent errors from occurring down the line.
Truthy & Falsy Values
In JavaScript, there’s truthy and falsy values. Truthy values are any value type that ISN’T one of the five following falsy values:
null, undefined, 0, '' (empty string), NaN
Using Boolean() on any of these falsy values will yield false; In fact, putting one of these falsy values as a condition in an if-else statement will cause unexpected results.
// Since height is a falsy value, "Height is UNDEFINED! >:(" will be logged to the console
const height = 0;
if (height) {
console.log('Yay! Height is defined! :D');
} else {
console.log('Height is UNDEFINED! >:(');
}
It is important to know if a value is truthy or falsy, as that will cause unexpected errors in the code if one doesn’t know them or how to deal with them.
The Ternary Operator
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if-else statement. – The MDN Web Documents.
// Example of a ternary operator const truth = true; const lie = false; // The console logs 'he speaks the truth!' since the variable "truth" is a truthy value (true, in this case) console.log(truth ? 'he speaks the truth!' : 'He lies!') // The console logs 'he lies!' since the variable "lie" is a falsy value (false, in this case) console.log(lie ? 'he speaks the truth!' : 'He lies!')
the ternary operator is used to make quick and easy comparisons all in one line, compared to if-else statements which requires a minimum of five lines. However, ternary operators can ONLY contain the three operands required to use it, no more, no less, making its usage limited.
