Introduction
JavaScript is one of the most widely used programming languages. It is also the language which is used for creating Rules and QScripts in Q, as well as one of the methods for creating variables. The below is a basic outline of the principals behind JavaScript that will allow you to write your own code.
Method
1. Declaring variables and statements
Unless you are using a simple formula, such as 1+2
, you will most likely need to declare variables to use in your formula. Variables in this context are declared identifiers that store a specific value and data type. Declared variables includes global variables, which are accessible from anywhere in your code, and local variables, which are only accessible within the block or function they are found in.
Best practice is to declare JavaScript variables first. Below is an example where we have declared 3 variables (b1, b2, b3) and then assigned a value to each using the single equals sign:
var b1, b2, b3;
b1 = "Brand 1";
b2 = "Brand 2";
b3 = "brand 3";
Note, variable names must start with a letter, underscore or dollar sign, and are case-sensitive.
Don't be confused between declared variables in JavaScript and variables that appear in your 'data set'. They both can play a role in your code, but are treated differently. For example, If I had a variable in my data set called q1 and I wanted to declare it in my code so I could perform a calculation with it, the below would create a declared variable called x:
var x = q1;
This would mean every time I reference x, it would represent all the data from my q1 variable.
There are several ways to declare JavaScript variables. Let’s now go over each of them.
Var
The var
command is the original method used for declaring variables. For example:
var brand1 = 3;
var brand2 = 5;
var total = brand1 + brand2;
Note, this method allows you to redefine each variable and change the data type. Each statement is separated by a semi-colon.
Let
Unlike var
, the newer let
command cannot be re-declared. It also has what is known as Block Scope. This means you can declare a variable within a {}
block and it will not be accessible outside it. For example:
{
let x = 5;
}
Const
Similar to let
, const
cannot be re-declared and it too possesses Block Scope. However, it additionally cannot be reassigned to a different data type. It is recommended to use const
with new arrays, objects, functions and regex expressions.
const brands = ["Brand 1","Brand 2", "Brand 3"];
2. Formulas
JavaScript formulas and expressions use all the traditional mathematical operators (i.e., +, -, /, (, ), and *):
(10 +2) * 5 // This equals 60
Standard mathematical functions are also available using the Math
object. For example, you can find the maximum and minimum of x by writing the below:
Math.max(x)
Math.min(x)
Formulas can be made conditional through using if..else
statements. For example:
if (x < 5) 1; // If x is less than 5, assign a 1
else if (x>=5 & x<10) 2; // if x is greater than or equal to 5 and less than 10, assign a 2
else 3; // otherwise assign a 3
See How to Work with Conditional JavaScript Formulas for further details on using mathematical and conditional formulas in JavaScript.
Note, the above example includes comments after the //
character. To do the same over multiple lines in a single block, enclose the commented text within /*
and */
.
3. Properties and methods
You can reference properties or methods of a declared variable by adding a full stop, followed by the property or method name.
For example, if we wanted to replace specific text within a string, we could do the following using the replace
method:
let temp = "This is my first test";
let result = temp.replace("first","final");
Here, we first define temp and then replace “first” with “final” to create result with the value of “this is my final test”.
If we wanted to instead work out how many characters in temp, we could use the length
property:
let result = temp.length; // This returns 21
See How to Manipulate Strings Using JavaScript for further examples and related functions.
4. Data types
The variable data type is important for telling the JavaScript code how to perform a specific function.
Numeric
By default, any assigned numeric value will be treated like a number:
var x = 5;
String
A string (or text) is wrapped in either single or double quotes:
var x = "Coke";
var x = "5";
Note you can also use quotes within a string but you need to make these different to the ones surrounding the string, e.g. var x = "'So-called' fans"
. Alternatively, you can precede the internal quote character with a backslash:
var x = "\"So-called\" fans";
Be careful when using both numbers and strings in a declaration. JavaScript will evaluate as a string as soon as it encounters this data type. For example:
var x = 11 + 5 + " Bottles" // Returns "16 Bottles"
var x = "Bottles" + 11 + 5 // Returns "Bottles115"
Boolean
Booleans will only ever return true or false and will use the double equals sign.
(v1 == v2)
Date
Date and time variables can be created via the new Date()
function which can accommodate string, millisecond and year, month, day declarations:
const date = new Date(); // Today's date
const date = new Date("09/08/2021");
new Date(2021, 08, 09);
Array
Arrays are items that can store multiple elements together within square brackets and separated by a comma.
const brands = ["Brand 1","Brand 2","Brand 3"];
Arrays are zero-based, so unlike other languages such as R, the first item has an index of 0 and the second item an index of 1.
See How to Work with JavaScript Arrays and Loops for greater detail on how to work with loops and arrays in JavaScript.
Object
Objects are contained within curly braces and are made up of properties that include a name and value, each separated by a comma.
const brand = {name:"Coke", variant:"Diet", type:"Can", size:50};
You can reference object properties via objectName.propertyName
or objectName["propertyName"]
. For example, brand.name
and brand["name"]
will both return Coke.
5. Functions
A function returns a result based on a set of statements and a series of pre-defined input values.
The format this takes is the function command, followed by a function name and brackets that contain references to the input values or arguments. The formula to be returned is then wrapped inside curly braces like below:
function thisFunction(x, y, z) {
return (x + y)/ z;
}
To use this function, it would be called by referencing its name and supplying the values for x, y and z:
thisFunction(2,4,5) // Returns 1.2
Alternatively:
let x = 2;
let y = 4;
let z = 5;
thisFunction(x,y,z)
Remember JavaScript is case-sensitive so ThisFunction is not the same as thisFunction. Functions can also appear in your code either before or after you use it in a call.
6. JS Coding Tips
You can improve readability by formatting your code as follows:
-
Write lots of comments to document what your JavaScript is meant to do. A comment starts with
//
. This is a great help if you are trying to figure out your script months later, or if someone else is reading your script.// Comments are ignored by JavaScript, but are a great help to you.
- Use the Tab key on your keyboard to make your code more readable. Whenever you write an
if/else/for
line, use Tab on the next line.if (result < 10) {
if (result < 5)
result = 5;
else
result = 10;
}
When writing JavaScript code, you need to be exact and pay attention to:
- The presence or absence of semi-colons: they signal that you’re ready for the next bit of the expression.
- The capitalization of letters: case-sensitivity means that dog does not equal Dog or DOG.
- The right number of brackets (and where they open/close).
- Whether brackets are (round) or {curly} or [square].
- When symbols are doubled: double ampersands (
&&
) for “AND”, double-equal signs (==
) for equality, and double pipes (||
) for "OR". - Index values: JavaScript is 0-based so the first iteration in a loop or array is 0, not 1.
- Missing values with your input variables: they can lead to missing results if not handled correctly. For example, if you are summing a set of variables (e.g.
q1 + q2 + q3
) and one of them returns a NaN (Not a number) for a particular record, the result for that record will also be NaN unless you explicitly address this using theisNaN
function or if statements.
Next
How to Work with Conditional JavaScript Formulas
How to Manipulate Strings Using JavaScript
How to Work with JavaScript Arrays and Loops
Comments
0 comments
Article is closed for comments.