Programming/JavaScript/General Syntax: Difference between revisions
Brodriguez (talk | contribs) (Add link) |
Brodriguez (talk | contribs) m (Brodriguez moved page Programming/JavaScript/Syntax to Programming/JavaScript/General Syntax) |
(No difference)
|
Revision as of 23:01, 22 February 2023
.js
See also Objects and Data Structures
General Language Notes
- String single and double quotes are interchangeable.
- Semi-colons required.
- Variable casing: camelCase.
- Variables are loosely typed.
- Scope controlled at variable creation.
Comments
Inline Comments
// This is an inline comment.
Block Comments
/** * This is a block comment. * Comment line 2. * Another block comment line. */
Basic Input and Output
Basic Output
The following will output a single line:
console.log('Hello World!');
The following will output multiple lines:
console.log('This is a test.'); console.log('This is line #2'); console.log('Outputting 3 lines total.');
Basic Input
Variables
Variable Declaration
let aBool = true; let bBool = false; let myVar1 = "This is "; let myVar2 = "a string.";
Variable Usage
// Print some variables, as-is. console.log('Printing variable values.'); console.log(aBool); console.log(bBool); // Print two variables concatenated together. console.log(myVar1 + myVar2); // Alternatively. console.log(`${myVar1} ${myVar2}`); // Combine two variables, then print the result. myVar3 = myVar1 + myVar2; console.log(myVar3);
Booleans
let trueBool = true; let falseBool = false;
Null Values
JavaScript uses the standard null
.
let nullValue = null;
Variable Scope
JavaScript has unique variable scope handling.
Aka, controlling where the variable can and cannot be accessed from.
This is controlled by the combination of how and where a variable is declared from.
The "var" Keyword
The original, default way to declare a variable was through var
. IE:
var myVar;
This has a few quirks compared to most languages. In summary:
- Any
var
declaration is processed before any other code, regardless of where it's declared.- A side-effect is that a variable declared this way can be referenced BEFORE it's actually declared. The result is that it will be "undefined" until it's actually declared.
- The scope of
var
variables automatically includes all inner scopes, such as nested functions.- If the variable is declared outside of any given scope, then it's automatically global.
The result is that larger files can easily have variables with unclear or hard to manage scope. Thus, using var
is not generally recommended.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var for full documentation on exact properties.
The "let" and "const" Keywords
The let
and const
keywords are newer ways to declare variables in JavaScript.
The const
keyword is used to declare an unchanging constant.
The let
keyword is used to create a variable that can change after declaration.
For both of these, the scope is much smaller than var
.
These declarations will only be visible within the code blocks they're defined within. This includes things like if statements. For example:
// Checking scope of variable x and y. function() { let x = 5; // Can see x. y not declared yet. if (true) { let y = 2; // Can see x and y. } else { // Can see x, but not y. } // Can see x, but not y. }
Generally, this scope handling is considered safer and more predictable. Thus it's now the preferred way to declare JavaScript variables.
Import Statements
If Statements
Note that JavaScript's {{{1}}}
is effectively equivalent to other language's {{{1}}}
, as far as conditional statements go.
Basic If
if (x === y) { # Logic if true. }
Full If
if (x === y) { # Logic if true. } else if (! x && (y || z) { # Logic for "else if" true. } else { # Logic for false. }
Ternary Operators
An alternative, if less-immediately-clear way to write if statements is to use "ternary operator" shorthand.
Syntax is as follows:
<conditional_statement> ? <true_clause> : <false_clause>
As an example:
x == y ? console.log('x and y match!') : console.log('x and y DO NOT match...');
Switch/Case Statements
General syntax is:
switch (<conditional_statement>) { case <result_1>: # Logic if matches <result_1>. break; case <result_2>: # Logic if matches <result_2>. break; ... default: # Default/fallback if matched no results. break; }
Note that the break
statements are optional, but recommended. Removing a break
statement will make the code execute into the next result section, instead of exiting the switch block.
Loops
Basic Loops
For loop:
for (let <counter_var> = <start_index>; <end_condition>; <counter_var_modifier> { # Loop logic here. }
Ex:
for (let index = 0; index < myArr.length; index++ { # Loop logic here. }
While Loop:
while (<condition>) { # Loop logic here. }
JavaScript Looping
ForEach loops through each element in an array, and is very useful.
ForEach Syntax:
<array_var>.forEach(<function_here>);
For example:
// ForEach as a standard function. myArr.forEach(function(arrItem) { # Loop logic here. } // ForEach as an arrow function. myArr.forEach(arrItem => console.log(arrItem));
Map is similar to forEach, except it returns a new array, with each array item modified by the loop logic. Ex:
myArr.map(number => { return number * 10; });
Functions
Basic Template
/** * Function description here. * @param <variable_name> <variable_description> * @return <return_val_description> */ function <function_name>(arg1, arg2, ..., argN) { # Function logic here. ... # If function has a return value, then return it with the following. return <variable_here>; }
Examples
Basic example:
function myFunc() { # Function logic here. }
Example with arguments.
function argFunc(my_int, my_string, some_other_arg) { # Function logic here. }
Example of arguments with defaults.
Defaults will be used if no corresponding arg is provided, OR if the provided arg is undefined
when the function is called.
function argFunc(my_int = 5, my_string = 'Example string', some_other_arg = true) { # Function logic here. }
Arrow Functions
Arrow function notation is a function syntax specific to JavaScript.
It tends to be very common, so it's good to know.
Other than being syntactically different, it gives the same effect as standard functions.
Basic format:
const <function_name> = (<arg1>, <arg2>, ..., <argN>) => { # Function logic here. }
Alternatively, a "condensed" format:
// Single line function. const <function_name> = (<arg1>, <arg2>, ..., <argN>) => # Single line here;
// Multi-line function. const <function_name> = (<arg1>, <arg2>, ..., <argN>) => { # Function logic here. }
For example:
const myCondensedFunc = (name, age) => console.log(`I am ${name} and I am ${age} years old.`);