Norman
Norman

Reputation: 6365

javascript variable shows as NaN when passed to a function

a=["s21aSi"]

gPf = function(a) {
    var c;
    a.forEach(function(b) {
        c = b
    })

    gPg(c);
    console.log('Inside gPf '+c)
}

gPg = function(z) {
    console.log('Inside gPg', +z)
}

gPf(a)

Why does z show as Nan when I do console.log inside gPg. It's a string inside gPf but show Nan when it's inside gPg

Upvotes: 0

Views: 88

Answers (3)

khaous
khaous

Reputation: 96

Because you are changing the signal of a Not-A-Number, when you add before a number a signal(+ or -) you are changing the signal of this number, when you add a signal before a string, the JS will convert this string in a number, but if the string doesn't seem to be valid number, JS will convert this to NaN, take a look at Nan Object on Mozilla's documentation to more details.

So to your code works as expected, you'll have to remove + before the variable z, like this:

a = ["s21aSi"]

gPf = function(a) {
  var c;
  a.forEach(function(b) {
    c = b
  })

  gPg(c);
  console.log('Inside gPf:', c)
}

gPg = function(z) {
  console.log('Inside gPg:', z)
}

gPf(a)

Upvotes: 2

Rick
Rick

Reputation: 1870

'Inside gPf '+c the plus sign (+) is being used to concatenate 2 strings.

'Inside gPg', +z the plus sign (+) is used as a math (addition) function

Upvotes: 0

max
max

Reputation: 467

delete '+' before z:

gPg = function(z) {
    console.log('Inside gPg', z)
}

or

gPg = function(z) {
    console.log(`Inside gPg ${z}`)
}

Upvotes: 4

Related Questions