Language Basics - SelfishHellfish/JS_Ref GitHub Wiki
JavaScript is executed in the browser. It is found between <script>
tags in an html file. Best practice is to place scripts at the end of the html <body>
. This ensures that the entire webpage loads prior to script execution, preventing page loading 'hang-ups' and ensuring that any tags the script refers to exist on the webpage. The <noscript>
tags may be optionally used to enclose a message that will be output when a user attempts to load a webpage with JS disabled.
For organization purposes, it is best practice to outsource JS script files and import them into the html document. Do so by including the src="file.js"
attribute in the <script>
tag. The script tag always occurs in pairs. If the scr attribute is specified, any JS code between the <script>
tags is ignored. Multiple JS script imports are common, each with its own <script>
tag pair. Libraries should be imported before personal scripts.
Variables are data structures that store values. They are initialized as such: var variable_name = value;
. Variable names may not start with a number. Data structure types that can be stored in variables include numbers, strings, booleans, arrays, objects etc. Integers and floats don't exist in JS; 6.5 is simply a number. typeof
may be used to assess value/variable types. Variables may be cleared by being set to null
. Objects are formatted as such:
var object1 = {variables/properties/fields: values/methods/functions};
Although certain syntactical elements aren't required for JS code to be executed, being explicit allows for optimization. To ensure that errors are thrown when you aren't being explicit, add the line "use strict";
to the top of your script. Examples of being explicit include ending lines with ;
and using the var
keyword when defining variables. ;
is not needed at the end of code blocks {}
, only at the end of statements. Be aware that if strict mode is enabled, third-party libraries must adhere to its criteria to avoid errors.
JS is case sensitive; var1 != Var1
. var
is only needed when creating new variables, not when reassigning variables. In reassigning variables, variables may change their types, since JS uses dynamic typing. Despite this freedom, it's generally good practice to maintain the same type when reassigning variables.
Variables can be declared after assigning a value to them, since in JS execution, the browser/JS engine will first assign all the declarations to undefined
. Then, these declarations are reassigned according to the order in which they appear in the script(s). However, a variable's initialization/assigning must occur prior to its usage.
Functions are blocks of code that can be called multiple times. JS function format:
function gc_content(argument1, argument2) {line; line; line;};
Functions may also be assigned to variables:
var fxname2 = gc_content; fxname2(argument1, argument2);
Control structures can be used to control the flow of code execution.
General JS if statement format:
if (condition) {line; line; line;} else if (condition2) {} else {};
, where condition must be true/false
e.g.1
x=[null,NaN,false,0,undefined,5]; for (var i = 0; i < x.length; i++){ if (x[i]){ console.log(i+' has a value'); } };
output: '5 has a value'
This form assesses whether the condition has a value. If so, it is interpreted as true. i.e. if the condition is one of [null,NaN,false,0,undefined]
, it does not have a value and the statement is interpreted as false. If x=5
and the condition is x>3
, then the condition is true and is interpreted to have a value of 1, thus proceeding.
e.g.2
x=[null,NaN,false,0,undefined,5]; for (var i = 0; i < x.length; i++){ if (x[i]==true){ console.log(i+' is true'); } };
no output
If x=5
and the condition is x>3
, then the condition is true and the contained code is executed.
JS switch statement format:
switch (variable) { case 3: console.log('is three'); break; default: console.log('default'); break; }
JS for loop format:
for (var i = 0; i < 5; i++) {};
For nested loops, continue;
and break;
only affect the immediate loop in which they are written, not any other wrapping/parent loops.
JS while loop format:
while (condition) {code};
or
`do {code} while (condition);
the latter will stop executing the conditional code ONCE the condition is false
In multiplication/division of floating numbers, JS has a bug that will incorrectly show a greater number of decimal places than is correct. Specify an answer's number of decimal place, like so:
(a*b).toFixed(2)
In comparing values, ===
and !==
evaluate the equality of values and of type. Important rules included NaN != NaN
, null
cannot be compared to anything except undefined
, in which case they are equal, and undefined
compared to anything is always false, except when compared to null
. Combine conditionals with &&
for 'and' and ||
for 'or'. If var test = true
, !test = false
.
The conditional (ternary) operator is a shortcut for the if statement:
console.log(a == b ? 'true' : 'false');
A list of JS operator precedence may be consulted on the MDN.
For a more concise summary, view the basics cheat sheet