Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to console log the name of a variable/function?

Tags:

javascript

I want to do this: log(variableOrFunction)

And be able to produce this: variableOrFunction: actualValue.

I tried this:

export const log = (value) => {
  console.log('' + value + ':', value)
  console.log(value)
}

But I get this instead: [object Object]:

What's the correct of doing this?

like image 237
alex Avatar asked Jan 04 '18 02:01

alex


People also ask

How do you find the console log of a variable?

If you want to do this to an object that has been already logged (one time thing), chrome console offers a good solution. Hover over the printed object in the console, right click, then click on "Store as Global Variable". Chrome will assign it to a temporary var name for you which you can use in the console.

Can I console log a function?

We can call any function inside a function, including console. log().

How do you write a function in console log?

Syntax: console. log(" "); Parameters: It accepts a parameter that can be an array, an object, or any message.

What function can be used with console log () to write objects to the console?

Method 3 — Use console. While console. log() will work for objects, there is a method specifically meant for displaying objects to the console called console. dir() . “The Console method dir() displays an interactive list of the properties of the specified JavaScript object.


2 Answers

You can log them with a pair of braces around them ({}), which will create an object with the name of the variable as the key:

function someFunction() {};

const someOtherFunction = () => {};

const someValue = 9;

console.log({someFunction});
console.log({someOtherFunction});
console.log({someValue});

const renamed = someFunction;

console.log({renamed})
like image 81
CRice Avatar answered Nov 02 '22 06:11

CRice


Built on @CRice answer:

const arr = [10, 20, 30, 40, 50]
const obj = { a: 10, b: 20, c: 30, d: { e: 40 } }
const str = "abcdef"

function slog(obj) {
  Object.entries(obj).forEach(([key, value]) => console.log(key + ":", value))
}

slog({ arr })  // arr: [ 10, 20, 30, 40, 50 ]
slog({ obj })   // obj: { a: 10, b: 20, c: 30, d: { e: 40 } }
slog({ str })   // str: abcdef
like image 36
Take Avatar answered Nov 02 '22 06:11

Take