Code Snippets #2 – VAR

posted in: Software Testing | 0

VAR short for variable. We can pretty much add anything as a variable, but for the sake of ease, I will restrict the snippets here to some straight forward approaches.

So the syntax is simply var + name = value you want to store under the given name and to complete the function you end it with a semi-colon. 

var nameOne = "some variable";
var two = 1;
var my_data = array.attribute;
var 3 = 1 + 1;
var myArray = [Mark, Dave, John, Kieran];

You declare that the following is a variable by using var, then you give it a name. This can be anything, but best to keep it simple and short. This name can be one word, multiple words, or a number. The conventional method for writing a name is to start lowercase, then add a title case for each new word (there can be no spaces). So for example: thisIsMyVariableName.

Why do we use variables?

Well, there is no straight forward answer as they come in handy for lots of different uses. One of the easiest answers is to keep your code length short. Imagine if you were using array.someData.someData multiple times, your file would soon get big. Using a variable means you can restrict this re-usage by giving it a name; myData for example. 

Another reason var is used is so you can perform really complex calculations, or process logic when combined with other functions such as  the for() function which will loop through your array. You can tell the var to +1 every time it sees a certain value which you can then output to the console.log()

So in short, var is very useful, but very easy to use. 

Here’s one you will find yourself using quite a bit when using Postman. It allows you to find data within your array from the response received. 

var data = JSON.parse(responseBody);

I hope you found this useful. Feel free to add comments and I will update this post with new ideas and usage for the VAR as and when they become apparent to me. 

Back

Leave a Reply