Undefined variable? encrypt/decrypt - javascript

Hey i am trying to make a simple encrypt/decrypt javascript. I am having a lot of trouble using variables from my first function into the second function.
the first function encrypts
2nd function decrypts
problem: I cannot use the variables I used in my first function. For example for "encoded" it keeps returning undefined! I attached my short code under.
var encoded;
function code(string, pass)
{
array=[]
for (var i = 0; i<string.length; i++)
{
//converts code into an array & unicode
b = (string.charCodeAt(i))
array.push(b)
}
//encovder
let encoded = array.map(function(x)
{
return x*pass
})
return encoded
}
(code("hello",7))
//decode
function decoded()
{
console.log(encoded)
}
console.log(decoded())

You should assign the value of the function to your variable in the relevant scope:
var encoded;
function code(string, pass){
array=[]
for (var i = 0; i<string.length; i++){
//converts code into an array & unicode
b = (string.charCodeAt(i))
array.push(b)
}
//encovder
let encoded = array.map(function(x){
return x*pass
})
return encoded
}
encoded = (code("hello",7));
By the way your result will be NaN because "hello".charCodeAt(5) is NaN and NaN * number == NaN.

Because you don't set the variable encoded that is defined on the first line, thus it value will be undefined when you try to log it.
WHY?
because inside code you redefine encoded on this line let encoded = ... and the later one shadows the one defined on the first line. So, here the second one gets set and not the first one (global one).
How to solve this?
You either not declare a new encoded inside the function (so this let encoded = ... should become this encoded = .... Or assign the returned value of code to the global encoded like this var encoded = code("hello", 7);.
An example of Variable Shadowing:
var value = 5;
console.log(value); // uses the above value
function foo(){
var value = 99; // redefining value (shadowing occur from this point)
console.log(value); // logs the newly defined value.
}// at this point, the value (99) gets destroyed.
foo();
console.log(value); // logs 5 as it is the one belonging to this scope no matter wether the value (99) gets destroyed or not.
Read more about Scopes and Variable shadowing and Variables lifetime.

Related

Javascript integer to string output not matching expected values

During some basic tests of JS usage I have been playing around with object generation / addition to an array. I have so far used two different approaches for this problem:
A single global object which has fields varied and then added.
A factory function which generates the same object with an additional operation to show a slight difference (Addition of 1 to the value field)
While there are no errors at run time the value field on the global object property always outputs a 2 (Where the value is suppose to increment with the loop), while the function approach seemingly works without issue. Do you have any idea why this would be the case?
The final output I generated was "[{"name":"Hello","value":2},{"name":"Hello World","value":1},{"name":"Hello","value":2},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]" (from the console.log(JSON.stringify(testArray));).
I had expected an output of "[{"name":"Hello","value":0},{"name":"Hello World","value":1},{"name":"Hello","value":1},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]"
The code for the relevant functions and object can be found below.
Defining the global variable:
var globalVariable =
{
name: undefined,
value: undefined
}
Factory function:
function globalVariableGen(name, valueInput)
{
return output =
{
name: name,
value: valueInput + 1
}
}
Array generation function:
function test2()
{
var i, testArray = [];
for (i = 0; i < 3; i++)
{
alert(i.toString());
globalVariable.name = "Hello";
globalVariable.value = i;
testArray.push(globalVariable);
testArray.push(globalVariableGen("Hello World", i));
}
console.log(JSON.stringify(testArray));
}
Kind regards,
Shadow
This is because javascript is pass-by-reference and you're referring to the same globalVariable which you add to the array multiple times. The array then contains multiple pointers to the globalVariable which is exactly the same.
If you add a console.log(JSON.stringify(testArray) into the loop you will see this behavior.
> "[{"name":"Hello","value":0},{"name":"Hello World","value":1}]"
> "[{"name":"Hello","value":1},{"name":"Hello World","value":1},{"name":"Hello","value":1},{"name":"Hello World","value":2}]"
> "[{"name":"Hello","value":2},{"name":"Hello World","value":1},{"name":"Hello","value":2},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]"

How to change a variable used as argument for function

I've looked around a little bit, and I haven't found a clear answer as to why when this proceeding code is ran, it returns myInt as 0. I've read posts about how the variable is only changed inside the function, but from my perspective, I don't see any reason why myInt cannot be changed. For refrence, this is in Javascript.
var myInt = 0;
function changeVar(x) {
x += 1;
}
changeVar(myInt);
console.log(myInt);
The reason myInt is not changing is that x has local scope (anything you do to x only affects the value of x inside of changeVar).
Here's how you could change myInt from changeVar():
var myInt = 0;
function changeVar() {
myInt += 1;
}
changeVar();
console.log(myInt);
If you want to change a variable by passing it as an argument, you should pass an object instead:
var myObject1 = {value: 0}
var myObject2 = {value: 10}
function changeVar(x) {
x['value'] += 1;
}
console.log(myObject1['value']);
console.log(myObject2['value']);
changeVar(myObject1);
console.log(myObject1['value']);
console.log(myObject2['value']);
I will expand on the example given by #N.Kern - here is a better example of how to change the initial variable passed in the function:
var myInt = 0;
function changeVar(x) {
return x += 1;
}
var y = changeVar(myInt);
console.log(y);
Now, the reason for this is offered by #Shekhar Chikara in the comment. Essentially, the value you're passing to the function is modified within the local scope of the function, but it's not actually assigned back (or saved in memory) to the globally declared variable. So when you log the original global variable, you get the unchanged value back. Thus, you want to simply save your functions' returned value to it's own variable.
This will get you started on researching more.
Hope this helps.

Referencing a number in a JavaScript multidimensional object

The code I have below uses a number as a dataset in a JavaScript object:
spacenum = spacedetails[1];
//Create object for space number
if(spacenum in spaceobj['P1'] == false){
spaceobj['P1'][spacenum] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
}
spaceobj['P1'][spacenum]['Vacant'] = spacedetails[2];
spaceobj['P1'][spacenum]['Name'] = spacedetails[3];
spaceobj['P1'][spacenum]['Number'] = spacedetails[4];
spaceobj['P1'][spacenum]['Apartment'] = spacedetails[5];
This code goes around in a loop so 'spacenum' starts at 1 and goes up to the late 100s.
I am trying to access the data like so:
console.log(spaceobj.P1.11.Vacant);
However, the '11' is throwing up errors. I've tried brackets and quotes without any luck.
How can I access the data I want using a number?
In javascript '11' is not a valid variable name. However, because of its dynamic nature you can use:
console.log(spaceobj.P1["11"].Vacant);
Alternatively, one can also use:
console.log(spaceobj["P1"]["11"].Vacant);
Actually your line code below is undefined
spaceobj['P1']
Be sure your spaceobj['P1'] = false; has value
spacenum = 11;
spaceobj = [];
spaceobj['P1'] = false;
spaceobj['P1'][spacenum]= 'A';
spaceobj['P1'][spacenum]= 'B';

String variable prefixed with undefined in for loop

I have a drop-down on which i use .Change() to trigger a function. Function basically get certain data using getJSON and based on those value in have to create string of array for mp3 file.
Below code is generating string but always prefix undefined to string.
In code you will notice setTimeout which is just to provide certain delay till data received. In below example i am using static value and it still prefix undefined. not sure why may be i have defined variable in wrong manner.
Complete example JSBin
$('.customSurah').change(function(){
//surahNo = $('#surah option:selected').val();
setTimeout(function(){
//countSpan = $('#surah-wrapper').children().length;
surahNo = 1;
countSpan = 7;
var i=0;
for (i = 0; i <= countSpan; i++) {
strCat += surahNo+"/"+i+".mp3,";
console.log(strCat);
}
}, 3000);
});
OUTPUT
undefined114/0.mp3,
undefined114/0.mp3,114/1.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,114/6.mp3,
You have a variable strCat that is not initialized, and then you append a value to it in this line:
strCat += surahNo+"/"+i+".mp3,";
Since strCat is not initialized in first round of loop, you get undefined prepended to your string.
To fix this, you need to initialize the variable to empty value first:
var strCat = ''; // <- initialize your variable to empty value
surahNo = 1;
countSpan = 7;
The outcome is perfectly valid as per javascript is concerned.
Why?
I guess you probably know if you declare any variable in javascript and you don't assign its default value then automatically undefined is assigned. So, that is a valid. What happens when you do that:
var somevar; // non assigned default value set to -> undefined
console.log(somevar); // logs undefined
But,
In your case you have to give it a default value like a blank string var strCat "";. So, now when you do this:
var somevar = ""; // assigned default value to set to -> ""
console.log(somevar); // logs ""
So, the solution to your issue is, you have to initialize/assign a default value to your variable. like:
var strCat = "";

Using a global variable in JavaScript

How do I do this?
My code is something like this:
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
var number = '10';
alert('' + [number] + '');
}
The first alert always returns 'old number was: ' and not 10. Shouldn't it return 10 on both alerts on the second function call?
By using var when setting number = '10', you are declaring number as a local variable each time. Try this:
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
number = '10';
alert('' + [number] + '');
}
Remove the var in front of number in your function. You are creating a local variable by
var number = 10;
You just need
number = 10;
The problem is that you're declaring a new variable named number inside of the function. This new variable hides the global number variable, so the line number = 10 assigns only to this new local variable.
You need to remove the var keyword from var number = 10.
Like in C, you need to define your variable outside of the function/method to make it global.
var number = 0;
function playSong(artist,title,song,id)
{
alert('old number was: '+[number]+'');
number = '10';
alert(''+[number]+'');
}
Let me explain in detail. To declare global variables and local variables in JavaScript
var firstNumber = 5; // Local variable
secondNumber = 10; // Global variable or window object
When your program is like this
var number = 1;
function playSong() {
alert(number);
var number = 2;
alert(number);
}
As per the JavaScript compiler, all declarations/initializations of variables will move to the top. This concept is called hoisting.
As per the compiler, the program will execute like:
var number; // Declaration will move to top always in Javascript
number = 1;
function playSong() {
var number;
alert(number); // Output: undefined - This is a local variable inside the function
number = 2;
alert(number); // Output: 2
}
If you need to access the global variable inside the function, use window.number.
var number = 1;
function playSong() {
var number = 2;
alert(window.number); // Output: 1 - From a global variable
alert(number); // Output: 2 - From local variable
}
You can also access it in any function like window.number, after removing var inside the function.
I’ve come across this answer in 2020 and after searching some more online I have found that apparently in the JavaScript definitions if you place variables outside of functions or even create a file called globals.js and just put all your globally required variables in that file, make that file the first user .js file in your script tags after jQuery and any other plugins you need, globals will load before your other scripts and allow you to call variables from globals.js within any script on the page.
W3C JavaScript Scope
I have tested this theory within a PHP application that I am building and I have been able to call variables from the globals.js file within a page that is loaded via Ajax to a jconfirm dialog for a troubleshooting wizard to set up the return values for when the dialog is closed.

Categories

Resources